LeetCode Learning 7

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];
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值