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]; } }; |
Reference:
http://binwu.net/leetcode/2015/04/25/Leetcode-House-Robber/
3 solutions
没有评论:
发表评论