198. House Robber
一、题目
Problem 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 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.
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.
Constraints:
0
<
=
n
u
m
s
.
l
e
n
g
t
h
<
=
100
0 <= nums.length <= 100
0<=nums.length<=100
0
<
=
n
u
m
s
[
i
]
<
=
400
0 <= nums[i] <= 400
0<=nums[i]<=400
二、题解
2.1 Approach #1 : Dynamic Programming
- Dynamic Programming关键三步骤:
· 定义子问题
· 设置边界和初始条件/递推基
· 方程/递推关系
此问题是一道经典的DP问题,我们可以根据DP问题三步骤来解决此问题。
-
定义子问题
抢nums[0,i]这个区间内的房子的最高金额
= 取nums[i]抢或不抢两种情况的最大值
= max(抢nums[i], 不抢nums[i]) (注:若抢nums[i],则nums[i-1]不能抢;反之,nums[i-1]可以抢)
= max(nums[i]+nums[0,i-2]区间内的最高金额, nums[0,i-1]区间内的最高金额)
用dp[i]表示抢nums[0,i]这个区间内的房子的最高金额,则原问题的解即为dp[]数组的最后一个元素值。 -
设置边界和初始条件
由于 dp[i] 与 dp[i-1] 和 dp[i-2] 有关系,循环过程涉及到了 i - 1 和 i - 2,所以循环初始化 i = 2,那么就要人为添加初始化边界条件和初始化条件如下:
边界条件:len = 0,输出 0; len = 1,输出 nums[0];
初始条件:dp[0] = nums[0]; dp[1] = max(dp[0], nums[1]) -
方程/递推关系
dp[i]=max(nums[i]+dp[i-2], dp[i-1])
Time complexity :
O
(
n
)
O(n)
O(n).
Space complexity :
O
(
n
)
O(n)
O(n).
//Dynamic Programming
//Time complexity : O(n); Space complexity : O(n)
class Solution {
public int rob(int[] nums) {
int len = nums.length;
if(len == 0 || nums == null) return 0;//边界条件1
if(len == 1) return nums[0];//边界条件2
int[] dp = new int[len];
dp[0] = nums[0];//初始条件1
dp[1] = Math.max(dp[0], nums[1]);//初始条件2
for(int i = 2; i < len; i++){
dp[i] = Math.max(nums[i] + dp[i-2], dp[i-1]);//递推关系
}
return dp[len-1];
}
}
2.2 Approach #2 : Optimization of Dynamic Programming
优化辅助空间:无需dp[],只需两个临时变量num_i2和num_i1来存储中间结果值dp[i-2]和dp[i-1]即可
Time complexity :
O
(
n
)
O(n)
O(n)
Space complexity :
O
(
1
)
O(1)
O(1)
//Dynamic Programming
//Time complexity : O(n); Space complexity : O(1)
class Solution {
public int rob(int[] nums) {
int len = nums.length;
//边界条件
if(len == 0 || nums == null) return 0;
if(len == 1) return nums[0];
//初始条件
int num_i2 = nums[0];//num_i2表示dp[i-2],初始化为dp[0]
int num_i1 = Math.max(num_i2, nums[1]);//num_i1表示dp[i-1],初始化为dp[1]
for(int i = 2; i < len; i++){
int num_i = Math.max(nums[i] + num_i2, num_i1);//递推关系;num_i表示dp[i]
num_i2 = num_i1;
num_i1 = num_i;
}
return num_i1;
}
}