关闭

House Robber

标签: leetcode
39人阅读 评论(0) 收藏 举报
分类:

题目:

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]=dp[i-1]+nums[i]  if  dp[i-1]==dp[i-2]

dp[i]=max(dp[i-2]+nums[i], dp[i-1])

根据这个动态规划等式,dp[i]为前i个house能偷到的最大数。

代码:

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




0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:11973次
    • 积分:1922
    • 等级:
    • 排名:千里之外
    • 原创:186篇
    • 转载:11篇
    • 译文:0篇
    • 评论:0条