House Robber

House Robber

问题:

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

思路:

  01 背包问题的变形而已

我的代码:

public class Solution {

    public int rob(int[] nums) {

        if(nums == null || nums.length == 0)    return 0;

        int len = nums.length;

        if(len == 1) return nums[0];

        if(len == 2) return Math.max(nums[0],nums[1]);

        int[] result = new int[len];

        result[0] = nums[0];

        result[1] = Math.max(nums[0],nums[1]);

        for(int j = 2; j < len; j++)

        {

            result[j] = Math.max(result[j-1],nums[j]+result[j-2]);

        }

        return result[len-1];

        

    }

}
View Code

 

你可能感兴趣的:(r)