LeetCode Learning 7

来源:互联网 发布:淘宝直通车助手 编辑:程序博客网 时间:2024/06/15 04:56

198. 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.

题意即从一个数组中取任意两两不相邻的数的子集,使其和最大。用动态规划的方法,设dp[n]是前n个数的解。显然dp[0]=nums[0],dp[1]=max(nums[0],nums[1])。从dp[2]起dp[n]其实可以通过比较dp[n-2]+nums[n]和dp[n-1]中较大的求得。即递推公式:dp[n]=max(dp[n-2]+nums[n],dp[n-1])。所以代码如下:
class Solution {public:    int rob(vector<int>& nums) {vector<int> dp;if(nums.size()==0)return 0;dp.push_back(nums[0]);if(nums[0]>nums[1])dp.push_back(nums[0]);else dp.push_back(nums[1]);for (int i = 2; i < nums.size(); i++){if (dp[i - 2] + nums[i] > dp[i - 1])dp.push_back(dp[i - 2] + nums[i]);else dp.push_back(dp[i - 1]);}return dp[nums.size() - 1];}};
213. House Robber II

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.

这道题是第一题的拓展,区别在在第一题的基础上,这题加上了首尾也相连,也可以看作围成圈的条件。这样与第一题不同的就在于第一和最后是不能同时取到的,但是还是可以沿用第一题的方法,但是需要分2种情况,把第一去掉和把最后一个去掉,计算出2种情况的解然后取较大的一个即是本题的解。代码如下:
class Solution {public:    int rob(vector<int>& nums) {        if(nums.size()==0)return 0;        if(nums.size()==1)return nums[0];        vector<int> dp;dp.push_back(nums[0]);if(nums[0]>nums[1])dp.push_back(nums[0]);else dp.push_back(nums[1]);for (int i = 2; i < nums.size()-1; i++){if (dp[i - 2] + nums[i] > dp[i - 1])dp.push_back(dp[i - 2] + nums[i]);else dp.push_back(dp[i - 1]);}vector<int> dp1;dp1.push_back(nums[1]);if (nums[2]>nums[1])dp1.push_back(nums[2]);else dp1.push_back(nums[1]);for (int i = 2; i < nums.size()-1; i++){if (dp1[i - 2] + nums[i+1] > dp1[i - 1])dp1.push_back(dp1[i - 2] + nums[i+1]);else dp1.push_back(dp1[i - 1]);}if (dp[nums.size() - 2]>dp1[nums.size() - 2])return dp[nums.size() - 2];else return dp1[nums.size() - 2];    }};


0 0
原创粉丝点击