#week7
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.
Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases. Also thanks to @ts for adding additional test cases.
分析:
动态规划类型
f[0,i]:从0到第i户,偷了第i户的最大结果
f[1,i]:从0到第i户,不偷第i户的最大结果
状态转移:
f[0][i] = max(f[1][i-1], f[0][i-1]);
f[1][i] = f[0][i-1] + nums[i];
初始化:
f[0][0] = 0;
f[1][0] = nums[0];
题解:
1 class Solution { 2 public: 3 int max(int a, int b) { 4 if (a > b) return a; 5 return b; 6 } 7 int rob(vector<int>& nums) { 8 int size = nums.size(); 9 if (size == 0) return 0; 10 int** f; 11 f = new int*[2]; 12 f[0] = new int[size]; 13 f[1] = new int[size]; 14 f[0][0] = 0; 15 f[1][0] = nums[0]; 16 for (int i = 1; i < size; i++) { 17 f[0][i] = max(f[1][i-1], f[0][i-1]); 18 f[1][i] = f[0][i-1] + nums[i]; 19 } 20 return max(f[0][size-1], f[1][size-1]); 21 } 22 };
看了其他人答案,化为一维也是可以的:
1 class Solution { 2 public: 3 int rob(vector<int>& nums) { 4 const int n = nums.size(); 5 if (n == 0) return 0; 6 if (n == 1) return nums[0]; 7 if (n == 2) return max(nums[0], nums[1]); 8 vector<int> f(n, 0); 9 f[0] = nums[0]; 10 f[1] = max(nums[0], nums[1]); 11 for (int i = 2; i < n; ++i) 12 f[i] = max(f[i-2] + nums[i], f[i-1]); 13 return f[n-1]; 14 } 15 };