198.打家劫舍
讲解链接:代码随想录-198.打家劫舍
public int rob(int[] nums) {
int[] dp = new int[nums.length];
dp[0] = nums[0];
dp[1] = Math.max(nums[0], nums[1]);
for (int i = 2; i < nums.length; i++) {
dp[i] = Math.max(nums[i] + dp[i - 2], dp[i - 1]);
}
return dp[dp.length - 1];
}
213.打家劫舍II
讲解链接:代码随想录-213.打家劫舍II
分两种情况开始偷。
public int rob(int[] nums) {
int len = nums.length;
if (len <= 3) {
int result = Integer.MIN_VALUE;
for (int i = 0; i < len; i++) {
result = Math.max(result, nums[i]);
}
return result;
}
// 从第一间屋子开始偷
int[] dp1 = new int[len];
dp1[0] = nums[0];
dp1[1] = Math.max(dp1[0], nums[1]);
// 遍历到倒数第二间屋子,因为最后一间屋子跟第一件是相连的。
for (int i = 2; i < len - 1; i++) {
dp1[i] = Math.max(nums[i] + dp1[i - 2], dp1[i - 1]);
}
// 从最后一间屋子开始偷
int[] dp2 = new int[len];
dp2[0] = nums[len - 1];
dp2[1] = Math.max(dp2[0], nums[0]);
for (int i = 2; i < len - 1; i++) {
dp2[i] = Math.max(nums[i - 1] + dp2[i - 2], dp2[i - 1]);
}
return Math.max(dp1[len - 2], dp2[len - 2]);
}
337.打家劫舍III
讲解链接:代码随想录-337.打家劫舍III
状态标记递归
// 3.状态标记递归
// 不偷:Max(左孩子不偷,左孩子偷) + Max(右孩子不偷,右孩子偷)
// root[0] = Math.max(rob(root.left)[0], rob(root.left)[1]) +
// Math.max(rob(root.right)[0], rob(root.right)[1])
// 偷:左孩子不偷+ 右孩子不偷 + 当前节点偷
// root[1] = rob(root.left)[0] + rob(root.right)[0] + root.val;
public int rob(TreeNode root) {
int[] res = robAction(root);
return Math.max(res[0], res[1]);
}
int[] robAction(TreeNode root) {
int res[] = new int[2];
if (root == null)
return res;
int[] left = robAction(root.left);
int[] right = robAction(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;
}
记忆化递归
不进行记忆化会超时
Map<TreeNode, Integer> map = new HashMap<>();
public int rob3(TreeNode root) {
if (root == null) return 0;
if (root.left == null && root.right == null) return root.val;
if (map.containsKey(root)) {
return map.get(root);
}
int curVal = root.val;
if (root.left != null) curVal += rob(root.left.left) + rob(root.left.right);
if (root.right != null) curVal += rob(root.right.left) + rob(root.right.right);
int childVal = rob(root.left) + rob(root.right);
map.put(root, Math.max(curVal, childVal));
return Math.max(curVal, childVal);
}