198.打家劫舍
class Solution {
public int rob(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int length = nums.length;
if (length == 1) {
return nums[0];
}
int[] dp = new int[length];
dp[0] = nums[0];
dp[1] = Math.max(nums[0], nums[1]);
for (int i = 2; i < length; i++) {
dp[i] = Math.max(dp[i - 2] + nums[i], dp[i - 1]);
}
return dp[length - 1];
}
}
213.打家劫舍II
题目链接:213. 打家劫舍 II - 力扣(LeetCode)
class Solution {
public int rob(int[] nums) {
if(nums.length == 1) {
return nums[0];
}
if(nums.length == 2) {
return Math.max(nums[1],nums[0]);
}
return Math.max(helper(nums,0,nums.length-1), helper(nums, 1, nums.length));
}
private int helper(int[] nums,int start, int end) {
int a = nums[start];
int b = Math.max(nums[start], nums[start+1]);
for(int i = start + 2; i < end; ++i) {
a = Math.max(a + nums[i],b);
int c = b;
b = a;
a = c;
}
return b;
}
}
337.打家劫舍III
题目链接:337. 打家劫舍 III - 力扣(LeetCode)
class Solution {
Map<TreeNode , Integer> map = new HashMap<>();
public int rob(TreeNode root) {
if(root == null) {
return 0;
}
if(map.containsKey(root)) {
return map.get(root);
}
if(root.left == null && root.right == null) {
return root.val;
} else if(root.left == null) {
int a = Math.max(rob(root.right),root.val + rob(root.right.left) + rob(root.right.right));
map.put(root, a);
return a;
} else if(root.right == null) {
int a = Math.max(rob(root.left), root.val + rob(root.left.left) + rob(root.left.right));
map.put(root, a);
return a;
} else {
int a = Math.max(rob(root.left) + rob(root.right), root.val + rob(root.right.left) + rob(root.right.right) + rob(root.left.left) + rob(root.left.right));
map.put(root, a);
return a;
}
}
}