LeetCode_198_House Robber_ loot

Topic Description: You are a professional thief to steal street plan of the house. Each room are in possession of some cash, the only constraints affecting steal your neighbor's house is equipped with anti-theft system communicate with each other, if two adjacent houses on the same night, thieves broke into the system will automatically alarm .
Given a representative from each non-negative integer array of Housing storage amount calculated in case you do not touch the alarm device, you can steal the maximum amount to.

输入示例1:
输入: [1,2,3,1]
输出: 4
解释: 偷窃 1 号房屋 (金额 = 1) ,然后偷窃 3 号房屋 (金额 = 3)。
     偷窃到的最高金额 = 1 + 3 = 4 。
输入示例2:
输入: [2,7,9,3,1]
输出: 12
解释: 偷窃 1 号房屋 (金额 = 2), 偷窃 3 号房屋 (金额 = 9),接着偷窃 5 号房屋 (金额 = 1)。
     偷窃到的最高金额 = 2 + 9 + 1 = 12 。

Algorithm thinking: dynamic programming
dynamic programming problem, define a dp array for storing up to a maximum value of the current income housing, dp [i] represents the maximum benefit when the i-th house.
State transition equation: dp [i] = max ( dp [i-1], dp [i-2] + nums [i]), i.e., when the i-th to the room, according to whether the house number of benefits should i additive to DP [i] on, and do not take into taking, or taking revenue earnings i-2 + i house number and house number, or do not take the house number of benefits i, i-1 directly proceeds house number. dp last one is the maximum benefit value.

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

Here Insert Picture Description

Guess you like

Origin blog.csdn.net/all_about_WZY/article/details/90727247