目录
LeetCode 198.打家劫舍
文章讲解:代码随想录
视频讲解:动态规划,偷不偷这个房间呢?| LeetCode:198.打家劫舍_哔哩哔哩_bilibili
力扣题目:LeetCode 198.打家劫舍
动态规划五步曲:
1.确定dp[i]的含义
dp[i]:包含i房间之前的房间所偷的最大金额为dp[i];
2.找出递推公式
dp[i] = Math.max(dp[i-2] + nums[i], dp[i-1]);
3.初始化dp数组
dp[0] = nums[0];
dp[1] = Math.max(nums[0], nums[1]);
4.确定遍历顺序
从前往后
5.打印dp数组
代码如下(Java):
class Solution {
public int rob(int[] nums) {
if(nums == null || nums.length == 0) return 0;
if(nums.length == 1) return nums[0];
int[] dp = new int[nums.length];
dp[0] = nums[0];
dp[1] = Math.max(dp[0], nums[1]);
for(int i = 2; i < nums.length; i++) dp[i] = Math.max(dp[i-1], dp[i-2]+nums[i]);
return dp[nums.length - 1];
}
}
LeetCode 213.打家劫舍II
文章讲解:代码随想录
视频讲解:动态规划,房间连成环了那还偷不偷呢?| LeetCode:213.打家劫舍II_哔哩哔哩_bilibili
力扣题目:LeetCode 213.打家劫舍II
动态规划五步曲:
1.确定dp[i]的含义
dp[i]:包含i以及之前的房间所偷窃的最大金额为dp[i]
2.找出递推公式
dp[i] = Math.max(dp[i-2] + nums[i], dp[i-1]);
3.初始化dp数组
dp[0] = nums[0];
dp[1] = Math.max(nums[0], nums[1]);
4.确定遍历顺序
从前往后遍历
5.打印dp数组
代码如下(Java):
class Solution {
public int rob(int[] nums) {
if(nums == null || nums.length == 0) return 0;
int len = nums.length;
if(len == 1) return nums[0];
return Math.max(robAction(nums, 0, len-1), robAction(nums, 1, len));
}
int robAction(int[] nums, int start, int end){
int x = 0, y = 0, z = 0;
for(int i = start; i < end; i++){
y = z;
z = Math.max(y, x + nums[i]);
x = y;
}
return z;
}
}
LeetCode 337.打家劫舍III
文章讲解:代码随想录
视频讲解:动态规划,房间连成树了,偷不偷呢?| LeetCode:337.打家劫舍3_哔哩哔哩_bilibili
力扣题目:LeetCode 337.打家劫舍III
代码如下(Java):
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int rob(TreeNode root) {
int[] res = robAction1(root);
return Math.max(res[0], res[1]);
}
int[] robAction1(TreeNode root){
int res[] = new int[2];
if(root == null) return res;
int[] left = robAction1(root.left);
int[] right = robAction1(root.right);
res[0] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
res[1] = root.val + left[0] + right[0];
return res;
}
}