1. 程式人生 > >House Robber問題及解法

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 andit 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 tonightwithout alerting the police.

問題分析:

作為一個強盜,去盜取一條街上住戶家裡的錢,但不能同時盜取相鄰的兩家的錢。

我麼可以這麼定義狀態:dp[i]----走到第i個住戶時,能盜取的錢的最大數目。

所以dp[i] = max(dp[i - 1], dp[i - 2] + nums[i - 1]),最終求得的dp[n]即為答案。

過程詳見程式碼:

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