算法分析与设计——LeetCode Problem.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[i] = max(dp[i-1], dp[i-2] + num[i])

代码如下

class Solution {
public:
	int rob(vector<int>& nums) {
		int leng = nums.size();
		if (leng == 0) return 0;
		if (leng == 1) return nums[0];
		if (leng == 2) return max(nums[0], nums[1]);
		int sum = 0;
		vector<int> maxVec(leng, 0);
		maxVec[0] = nums[0];
		maxVec[1] = max(nums[0], nums[1]);
		for (int i = 2; i < leng; i++) {
			maxVec[i] = max(maxVec[i - 1], maxVec[i - 2] + nums[i]);
		}
		return maxVec[leng - 1];
	}
};


猜你喜欢

转载自blog.csdn.net/sysu_chan/article/details/78930078