1. House Robber
题目要求:
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.
该题相当于从一个数组中取出一个或多个不相邻的数,使其和最大。具体代码如下:
1 class Solution { 2 public: 3 int rob(vector<int>& nums) { 4 int sz = nums.size(); 5 int * dp = new int[sz]; 6 for(int i = 0; i < sz; i++) 7 { 8 if(i == 0) 9 dp[0] = nums[0]; 10 else if(i == 1) 11 dp[1] = max(nums[1], nums[0]); 12 else 13 dp[i] = max(nums[i] + dp[i - 2], dp[i - 1]); 14 } 15 return dp[sz - 1]; 16 } 17 };
2. House Robber II
题目要求:
Note: This is an extension of House Robber.
After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street.
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 @Freezen for adding this problem and creating all test cases.
对于环形,主要考虑两种情况:
1) 第一个房子被偷:那么此时第二个房子和最后一个房子都不能被偷了,即我们可以从第三个房子到倒数最后一个房子之间用线性的动态规划求解。
2) 第一个房子没有被偷:那么此时我们可以从第二个房子到最后一个房子之间用线性的动态规划求解。
具体代码如下:
1 class Solution { 2 public: 3 int simpleRob(vector<int>& nums, int start, int end) { 4 int sz = end - start + 1; 5 int * dp = new int[sz]; 6 for(int i = 0; i < sz; i++) 7 { 8 if(i == 0) 9 dp[0] = nums[start]; 10 else if(i == 1) 11 dp[1] = max(nums[start + 1], nums[start]); 12 else 13 dp[i] = max(nums[start + i] + dp[i - 2], dp[i - 1]); 14 } 15 return dp[sz - 1]; 16 } 17 18 int rob(vector<int>& nums) { 19 int sz = nums.size(); 20 if(sz == 0) 21 return 0; 22 else if(sz == 1) 23 return nums[0]; 24 else 25 return max(simpleRob(nums, 0, sz - 2), simpleRob(nums, 1, sz - 1)); 26 } 27 };