题目:198. 打家劫舍
思路:动态规划dp。时间复杂度0(n),细节看注释。
C++版本:
class Solution {
public:
int rob(vector<int>& nums) {
int n=nums.size();
if(n<1) return 0;
//状态f[i]表示:打劫前i家(i:1-n)房屋的最高金额
vector<int> f(n+1,0);
//边界初始化
f[0]=0;
f[1]=nums[0];
for(int i=2;i<=n;i++){
//f[i-1]:表示不打劫第i家房屋带来的最大金额
//f[i-2]+nums[i-1]:表示打劫第i家房屋带来的最大金额
f[i]=max(f[i-1],f[i-2]+nums[i-1]);
}
return f[n];
}
};
JAVA版本:
class Solution {
public int rob(int[] nums) {
int n=nums.length;
if(n<1) return 0;
//状态f[i]表示:打劫前i家(i:1-n)房屋的最高金额
int[] f=new int[n+1];
//边界初始化
Arrays.fill(f,0);
f[1]=nums[0];
for(int i=2;i<=n;i++){
//f[i-1]:表示不打劫第i家房屋带来的最大金额
//f[i-2]+nums[i-1]:表示打劫第i家房屋带来的最大金额
f[i]=Math.max(f[i-1],f[i-2]+nums[i-1]);
}
return f[n];
}
}