码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode - House Robber

时间:2015-04-29 23:19:17      阅读:148      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!