原题链接:
https://leetcode.cn/problems/house-robber/description/
解法1
动态规划
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
class Solution { public: int rob(vector<int>& nums) { int n = nums.size(); int f[n + 2]; memset(f,0,sizeof f); for(int i = 0 ; i < n ; i++){ f[i + 2] = max(f[i + 1],f[i] + nums[i]); }
return f[n + 1]; } };
|
扩展: 环形打家劫舍 leetcode213
原题链接:
https://leetcode.cn/problems/house-robber-ii/description/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
|
class Solution { public: int rob(vector<int>& nums) { int n = nums.size(); int f1[n + 2],f2[n + 2]; memset(f1,0,sizeof f1); memset(f2,0,sizeof f2);
for(int i = 2 ; i < n - 1; i++){ f1[i + 2] = max(f1[i + 1] , f1[i] + nums[i]); }
f2[0] = 0; for(int i = 1 ; i < n ; i++){ f2[i + 2] = max(f2[i + 1], f2[i] + nums[i]); }
return max(f1[n] + nums[0],f2[n + 1]); } };
|