2015年6月9日星期二

LeetCode: House Robber

Dynamic programming.
Let rec[i] keep recording the maxim money with (i+1) houses.
Key is rec[i]=max(rec[i-1],rec[i-2]+nums[i]). 

TIP: Make sure allocate memory for vector, or in leetcode test will display runtime error which equals to core dump in c++ compiler.

Debugging for too long time, not happy...

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
public:
    int rob(vector<int>& nums) {
        if(nums.size()==0) return 0;
        if(nums.size()==1) return nums[0];
        vector<int> rec(nums.size());
        rec[0]=nums[0];
        rec[1]=max(nums[0],nums[1]);
        for(int i=2;i<nums.size();i++){
            rec[i]=max(rec[i-1],rec[i-2]+nums[i]);
        }
        return rec[nums.size()-1];
    }
};
There is another solution that recording money based on odd and even.

Reference:
http://binwu.net/leetcode/2015/04/25/Leetcode-House-Robber/
3 solutions

没有评论:

发表评论