LeetCode 0198 House Robber
作者:互联网
1. 题目描述
2. Solution 1
1、思路分析
Dynamic Programming
Intuition: At every i-th house we have two choices to make, i.e., rob the i-th house or don't rob it.
Case1 : Don't rob the i-th house - then we can rob the i-1 th house...so we will have max money robbed till i-1 th house.
Case 2 : Rob the i-th house - then we cann't rob the i-1 th house but we can rob i-2 th house....so we will have max money robbed till i-2 th house + money of i-th house.
Example:
1.) If the array is [1,5,3] then robber will rob the 1st index house because arr[1] > arr[0]+arr[2] (i.e., at
last index, arr[i-1] > arr[i-2]+arr[i])
2.) If the array is [1,2,3] then robber will rob the 0th and 2nd index house because arr[0]+arr[2] > arr[1] (i.e
., at last index, arr[i-2] + arr[i] > arr[i-1])
1》状态定义: dp[i] 表示偷第i户人家后获得的最大收益。
2》边界: dp[0] = nums[0], dp[1] = max{nums[0], nums[1]};
3》状态转移方程:
dp[i] = max{nums[i] + dp[i-2], dp[i-1]};
case 2 case 1
2、代码实现
package Q0199.Q0198HouseRobber;
/*
Dynamic Programming
Intuition: At every i-th house we have two choices to make, i.e., rob the i-th house or don't rob it.
Case1 : Don't rob the i-th house - then we can rob the i-1 th house...so we will have max money robbed till i-1
th house
Case 2 : Rob the i-th house - then we cann't rob the i-1 th house but we can rob i-2 th house....so we will have
max money robbed till i-2 th house + money of i-th house.
Example:
1.) If the array is [1,5,3] then robber will rob the 1st index house because arr[1] > arr[0]+arr[2] (i.e., at
last index, arr[i-1] > arr[i-2]+arr[i])
2.) If the array is [1,2,3] then robber will rob the 0th and 2nd index house because arr[0]+arr[2] > arr[1] (i.e
., at last index, arr[i-2] + arr[i] > arr[i-1])
*/
public class Solution {
public int rob(int[] nums) {
if (nums.length == 1) return nums[0];
// 1. 状态定义,i-th house的收益
int[] dp = new int[nums.length];
// 2. 初始状态
dp[0] = nums[0];
dp[1] = Math.max(nums[0], nums[1]);
for (int i = 2; i < nums.length; i++)
// 3. 状态转移方程 Case 2 Case 1
dp[i] = Math.max(nums[i] + dp[i - 2], dp[i - 1]);
return dp[nums.length - 1];
}
}
3、复杂度分析
时间复杂度: O(n)
空间复杂度: O(n)
3. Solution 2
1、思路分析
降低空间复杂度。用变量代替数组。
2、代码实现
package Q0199.Q0198HouseRobber;
public class Solution2 {
public int rob(int[] nums) {
/*
思路: Dynamic Programming
设f(k)=从前k个house中抢到的最大金额,A[i]=第i个house中的金额
n = 1, f(1) = A[1]
n = 2, f(2) = max(A[1], A[2])
n = 3, f(3) = A[3] + A[1], if rob the third house
or f(3) = A[2] , if don't rob the third house
==> transition equation: f(k) = max( (f(k-2) + A[k]), f(k-1))
Time complexity: O(n), where n is the length of nums.
Space complexity: O(1)
*/
int prevMax = 0;
int currMax = 0;
for (int x : nums) {
int temp = currMax;
currMax = Math.max(prevMax + x, currMax);
prevMax = temp;
}
return currMax;
}
}
3、复杂度分析
时间复杂度: O(n)
空间复杂度: O(1)
标签:arr,nums,House,rob,0198,th,house,LeetCode,dp 来源: https://www.cnblogs.com/junstat/p/16329088.html