House Robber

原创 2016年08月28日 14:44:23

题目:

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




LeetCode #337 - House Robber III - Medium

ProblemThe thief has found himself a new place for his thievery again. There is only one entrance to...
  • Arcome
  • Arcome
  • 2016年11月09日 18:54
  • 155

Leetcode 213 House Robber II 抢劫最大金额

HouseRobber扩展:抢劫完那条街道上的房子之后,这个贼有找到了实施自己盗窃行动的另一个地点,这样他才不会引来太多注意。这次,这里的搜有房子排成了一个圆圈,这意味着第一个房子和最后一个房子也是挨...

198. House Robber(C++实现)

动态规划求解,设n-2座房子最多能抢到f(n-2),n-1座房子能最多抢到f(n-1),n座房子最多能抢f(n),最后一座房子里有nMoney, 则可以推导出他们之间的关系(分两种情况,第一种不抢最后...

leetcode 213. House Robber II

After robbing those houses on that street, the thief has found himself a new place for his thievery ...

LeetCode:House Robber III

House Robber III Total Accepted: 13977 Total Submissions: 37027 Difficulty: Medium ...

LeetCode#198. House Robber

You are a professional robber planning to rob houses along a street. Each house has a certain amount...

LeetCode No.213 House Robber II

LeetCode No.213 House Robber II

Uber面试题2 | House Robber III

题目描述  小偷找到了一个新的偷盗地点,这里地区的房子组成了一棵二叉树,地区的入口是二叉树的根所在的房子。如果小偷同时偷窃了两个直接相邻的房子,就会触发警报器。求在不触发警报器的情况下小偷可以抢...

LeetCode-213. House Robber II

Note: This is an extension of House Robber. After robbing those houses on that street, the thief ha...

leetcode--House Robber II

House Robber II
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:House Robber
举报原因:
原因补充:

(最多只允许输入30个字)