首页 > 代码库 > leetcode 198 House Robber
leetcode 198 House Robber
暴力搜索:
public class Solution {
public int search(int idx, int[] nums){
if(idx<0){
return 0;
}
return Math.max(nums[idx] + search(idx-2, nums), search(idx - 1, nums));
}
public int rob(int[] nums) {
return search(nums.length-1, nums);
}
}
时间复杂度2^n,超时。
动态规划,存储中间值:
public class Solution {
public int rob(int[] nums) {
if(nums.length == 0){
return 0;
}
int[] f = new int[nums.length+1];
f[0]=0;
f[1]=nums[0];
for(int i=2; i<=nums.length; ++i){
f[i] = Math.max(nums[i-1]+f[i-2], f[i-1]);
}
return f[nums.length];
}
}
leetcode 198 House Robber