###### tags: `Leetcode` `medium` `dynamic programming` `python` `c++` `Top 100 Liked Questions` # 198. House Robber ## [題目連結:] https://leetcode.com/problems/house-robber/description/ ## 題目: 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 systems connected and **it will automatically contact the police if two adjacent houses were broken into on the same night**. Given an integer array ```nums``` representing the amount of money of each house, return the maximum amount of money you can rob tonight **without alerting the police**. **Example 1:** ``` Input: nums = [1,2,3,1] Output: 4 Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4. ``` **Example 2:** ``` Input: nums = [2,7,9,3,1] Output: 12 Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). Total amount you can rob = 2 + 9 + 1 = 12. ``` ## 解題想法: * 題目為: 小偷要搶錢,但是不能連續搶鄰居,求能搶的最大值 * 透過DP: * dp[i]表示搶到第i個房子時候 * 轉移方程: * dp[i]=max(dp[i-2]+nums[i],dp[i-1]) * 因為不能搶鄰居,所以考慮當前nums[i]是否搶時: * 選擇dp[i-2]+nums[i] * 或是不搶nums[i],繼承dp[i-1] * 對於初始: * dp[0]=nums[0] * **dp[1]=max(nums[0],nums[1])** * 因為不能打劫相鄰的房子,所以搶nums[0] or nums[1] ## Python: ``` python= class Solution(object): def rob(self, nums): """ :type nums: List[int] :rtype: int """ #time space: O(n) #dp[i]表示搶到第i個房子 #dp[i]=max(dp[i-2]+nums[i],dp[i-1]) if len(nums)==1: return nums[0] dp = [0]*(len(nums)) #初始 dp[0]=nums[0] dp[1]=max(nums[0],nums[1]) for i in range(2,len(nums)): dp[i]=max(dp[i-2]+nums[i],dp[i-1]) return dp[-1] result = Solution() nums = [2,7,9,3,1] ans = result.rob(nums) print(ans) ``` ## C++: ``` cpp= #include<bits/stdc++.h> using namespace std; class Solution { public: int rob(vector<int>& nums) { int n=nums.size(); vector<int> dp(n); //init dp: size=n, val=0 if (n==1) return nums[0]; dp[0]=nums[0]; dp[1]=max(nums[0],nums[1]); for (int i=2; i<n; i++){ dp[i]=max(dp[i-2]+nums[i], dp[i-1]); } return dp[n-1]; } }; int main(){ Solution res; vector<int> nums={2,7,9,3,1}; int ans=res.rob(nums); cout<<ans<<endl; //12 return 0; } ```