https://leetcode.com/problems/house-robber/description/
解题思路:
- 计算当前index的sum值
代码如下:
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];
else if(len == 2) return Math.max(nums[0], nums[1]);
int[] dp = new int[len];
dp[0] = nums[0]; dp[1] = Math.max(nums[0], nums[1]);
for (int i = 2; i < len; i++){
dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i]);
}
return dp[len - 1];
}
}
https://leetcode.com/problems/house-robber-iii/description/
解题思路:
-
计算当前index的sum值,然后比较array最后index和index-1的sum值就好了
class Solution {
public int rob(int[] nums) {int len = nums.length; if(len <= 0) return 0; else if(len == 1) return nums[0]; else if(len == 2) return Math.max(nums[0],nums[1]); int[] forward = new int[len]; int[] back = new int[len]; forward[0] = nums[0]; forward[1] = Math.max(nums[0],nums[1]); back[1] = nums[1]; back[2] = Math.max(nums[1],nums[2]); for(int i = 2; i < len - 1; i++){ forward[i] = Math.max(forward[i-1], forward[i-2] + nums[i]); } for(int i = 3; i < len; i++){ back[i] = Math.max(back[i-1], back[i-2] + nums[i]); } return Math.max(forward[len - 2], back[len-1]);
}
}
网友评论