198. House Robber
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.
题目解析:
- 当前状态只与前两个有关,可以使用动态数组减少内存
代码:
class Solution {
public int rob(int[] nums) {
if (nums.length == 1) return nums[0];
int[] dp = new int[2];
dp[0] = 0;
dp[1] = nums[0];
for (int i = 2; i <= nums.length; i++) {
dp[i%2] = Math.max(dp[(i - 1)%2], dp[(i - 2)%2] + nums[i-1]);
}
return dp[nums.length%2];
}
}
213. House Robber II
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system 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.
题目解析:
- 首尾相连,所以首尾不能同时选中,可以分成两种情况:不考虑首元素和不考虑尾元素
代码:
class Solution {
public int rob(int[] nums) {
if (nums.length == 1) return nums[0];
int n = nums.length;
int[] head = new int[2];
head[0] = 0;
head[1] = nums[0];
int[] tail = new int[2];
tail[0] = 0;
tail[1] = nums[1];
for (int i = 2; i < n; i++) {
head[i % 2] = Math.max(head[(i-1) % 2], head[(i-2) % 2] + nums[i - 1]);
tail[i % 2] = Math.max(tail[(i-1) % 2], tail[(i-2) % 2] + nums[i]);
}
return Math.max(head[(n-1) % 2], tail[(n-1) % 2]);
}
}
337. House Robber III
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called root.
Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if two directly-linked houses were broken into on the same night.
Given the root of the binary tree, return the maximum amount of money the thief can rob without alerting the police.
题目解析:
- 使用两个值来表示当前节点是否选择
- 如果选择当前节点,那么左右子节点都必须为不选
- 如果不选当前节点,那么左右子节点可以选也可以不选,选择最大值
- 可以用后序遍历来从下往上遍历
代码:
class Solution {
public int rob(TreeNode root) {
int[] result = postorderDfs(root);
return Math.max(result[0], result[1]);
}
public int[] postorderDfs(TreeNode root) {
if (root == null) {
return new int[]{0, 0};
}
int[] left = postorderDfs(root.left);
int[] right = postorderDfs(root.right);
return new int[]{Math.max(left[0], left[1]) + Math.max( right[0], right[1]), root.val + left[0] + right[0]};
}
}