leetcode-198. House Robber
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.
Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases. Also thanks to @ts for adding additional test cases.
Subscribe to see which companies asked this question
先用暴力来求解
int search(const vector<int>& nums, int index) { if (index >= nums.size())return 0; return max(nums[index] + search(nums, index - 2),//偷这家 search(nums, index - 1));//不偷这家 return 0; } int rob(const vector<int>& nums) { return search(nums, nums.size()-1);//2^n return 0; }
然后超时了,分析原因是很多相同的计算浪费了大量时间,比如递归中index=3肯定是包含了index=2的
可以用一个数组来存储从当前位置搜索的结果,然后暴力可以转换为DP,自底向上根据递归式递推出下一个状态,状态0 是0,状态1下只能偷取第一家 自底向上根据递归式递推出下一个状态
int rob(const vector<int>& nums) { int *arr=new int[nums.size()+10]; memset(arr, 0, (sizeof (int))*(nums.size()+10)); arr[0] = 0; arr[1] = nums[0]; for (int i = 2; i <= nums.size(); i++) { arr[i] = max(nums[i-1] + arr[i - 2], arr[i - 1]); } return arr[nums.size()]; return 0; }