LeetCode之“动态规划”:House Robber && House Robber II

时间:2024-01-05 11:31:14

  House Robber题目链接

  House Robber II题目链接

  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.

   该题相当于从一个数组中取出一个或多个不相邻的数,使其和最大。具体代码如下:

 class Solution {
public:
int rob(vector<int>& nums) {
int sz = nums.size();
int * dp = new int[sz];
for(int i = ; i < sz; i++)
{
if(i == )
dp[] = nums[];
else if(i == )
dp[] = max(nums[], nums[]);
else
dp[i] = max(nums[i] + dp[i - ], dp[i - ]);
}
return dp[sz - ];
}
};

  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) 第一个房子没有被偷:那么此时我们可以从第二个房子到最后一个房子之间用线性的动态规划求解。

  具体代码如下:

 class Solution {
public:
int simpleRob(vector<int>& nums, int start, int end) {
int sz = end - start + ;
int * dp = new int[sz];
for(int i = ; i < sz; i++)
{
if(i == )
dp[] = nums[start];
else if(i == )
dp[] = max(nums[start + ], nums[start]);
else
dp[i] = max(nums[start + i] + dp[i - ], dp[i - ]);
}
return dp[sz - ];
} int rob(vector<int>& nums) {
int sz = nums.size();
if(sz == )
return ;
else if(sz == )
return nums[];
else
return max(simpleRob(nums, , sz - ), simpleRob(nums, , sz - ));
}
};