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.
Example 1:
Input: [1,2,3,1] Output: 4 Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4.
Example 2:
Input: [2,7,9,3,1] Output: 12 Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). Total amount you can rob = 2 + 9 + 1 = 12.
思路一:递归
定义dfs(i)表示从第i家开始所能偷到的最多钱数。
如果小偷偷了第i家,那么他就不能偷第i + 1家了。如果不偷第i家,他就可以选择偷或者不偷第i + 1家。
递归方程如下:
dfs(i) = max(nums[i] + dfs(i + 2), dfs(i + 1)) if 0 =< i <= n-1
dfs(i) = 0 if i >= n
1 class Solution { 2 public: 3 int rob(vector<int>& nums) { 4 int len = nums.size(); 5 return dfs(0, len, nums); 6 } 7 private: 8 int dfs(int i, int len, vector<int> nums) { 9 if (i >= len) 10 return 0; 11 int steal = nums[i] + dfs(i + 2, len, nums); 12 int nosteal = dfs(i + 1, len, nums); 13 return max(steal, nosteal); 14 } 15 };
思路二:记忆化搜索
1 class Solution { 2 public: 3 int rob(vector<int>& nums) { 4 int len = nums.size(); 5 vector<int> dp(len, -1); 6 return dfs(0, len, nums, dp); 7 } 8 private: 9 int dfs(int i, int len, vector<int> nums, vector<int> &dp) { 10 if (i >= len) 11 return 0; 12 if (dp[i] > 0) 13 return dp[i]; 14 int steal = nums[i] + dfs(i + 2, len, nums, dp); 15 int nosteal = dfs(i + 1, len, nums, dp); 16 dp[i] = max(steal, nosteal); 17 return dp[i]; 18 } 19 };
思路三:动态规划
dp[i]表示[0, ..., i]家能偷到的最大钱数。
dp[i] = max(dp[i - 1], dp[i - 2] + nums[i])
dp[0] = nums[0]
dp[1] = max(dp[0], nums[1])
1 class Solution { 2 public: 3 int rob(vector<int>& nums) { 4 int len = nums.size(); 5 if (len == 0) 6 return 0; 7 if (len == 1) 8 return nums[0]; 9 if (len == 2) 10 return max(nums[0], nums[1]); 11 int dp[len] = {0}; 12 dp[0] = nums[0]; 13 dp[1] = max(dp[0], nums[1]); 14 for (int i = 2; i < len; i++) { 15 dp[i] = max(dp[i - 1], dp[i - 2] + nums[i]); 16 } 17 return dp[len - 1]; 18 } 19 };
进一步优化:状态转移函数只用了之前的两个状态,可以进一步优化空间复杂度。
1 class Solution { 2 public: 3 int rob(vector<int>& nums) { 4 int len = nums.size(); 5 int prev = 0, cur = 0; 6 for (int i = 0; i < len; i++) { 7 int temp = max(prev + nums[i], cur); 8 prev = cur; 9 cur = temp; 10 } 11 return cur; 12 } 13 };
时间复杂度:O(n), 空间复杂度O(1)