首页 > 其他 > 详细

leetcode - House Robber

时间:2015-04-29 23:18:21      阅读:279      评论:0      收藏:0      [点我收藏+]

leetcode - house-robber

https://leetcode.com/problems/house-robber/

Q:

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.

 

 1 class Solution{
 2 public:
 3     int rob(vector<int>& nums){
 4         int len = nums.size();
 5         if(len==0) return 0;
 6         if(len==1) return nums[0];
 7         vector<int> value(len+1,0);
 8         value[0] = 0;
 9         value[1] = nums[0];
10         for(int i=2; i<len+1; i++){
11             value[i]=max( value[i-1], value[i-2]+nums[i-1]);
12         }
13         return value[len];
14     }
15 };

 思路: 应该是动态规划 dp 问题。 之前没写过……一开始写成了递归,超时了。

后来看了一下别人的代码,都是用数组来存储数据的。

References:

http://www.cnblogs.com/ganganloveu/p/4417485.html

http://www.cnblogs.com/sdjl/articles/1274312.html

另一种写法:

http://www.meetqun.com/thread-8304-1-1.html

 之前写的错的:

class Solution{
public:
    int rob(vector<int>& nums) {
        if(nums.size()==1) return nums[0];
      //  int len = num.size();
        //vector<int>::iterator iter1 = nums.begin();
        //vector<int>::iterator iter2 = nums.end()-1;
        vector<int> subnums1(nums.begin(), nums.end()-1);
        vector<int> subnums2(nums.begin(), nums.end()-2);
        return max( rob(subnums1), rob(subnums2)+ *(nums.end()-1));

    }
};

 

leetcode - House Robber

原文:http://www.cnblogs.com/shnj/p/4467572.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!