代码随想录训练营第四十八天 | 动态规划()-其他
代码随想录训练营第四十八天 | 动态规划()
今天是训练营的第四十八天,开始了动态规划的强盗问题
198. 打家劫舍
class Solution {
public int rob(int[] nums) {
int n = nums.length;
if(n==1){
return nums[0];
}
int[] dp = new int[n+1];
dp[0] = nums[0];
dp[1] = Math.max(nums[0], nums[1]);
for(int i = 2; i< n; i++){
dp[i] = Math.max(dp[i-1], dp[i-2]+nums[i]);
}
return dp[n-1];
}
}
dp[i]的值要么是不相邻的前一个房子的总值加上现在的,要么可能是之前相邻的房子的值。
213. 打家劫舍2
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;
}
}
要考虑到成环的情况
337. 打家劫舍3
class Solution {
public int rob(TreeNode root) {
int result = steal(root);
return result;
}
public int steal(TreeNode root){
if(root == null){
return 0;
}
int son = steal(root.left);
son += steal(root.right);
if(root.left != null){
if(root.left.left!= null){
root.val += root.left.left.val;
}
if(root.left.right!= null){
root.val += root.left.right.val;
}
}
if(root.right != null){
if(root.right.left!= null){
root.val += root.right.left.val;
}
if(root.right.right!= null){
root.val += root.right.right.val;
}
}
root.val = Math.max(root.val, son);
return root.val;
}
}
不能层序遍历
今天好像是抢劫问题的唯一一天了
————————
今天是训练营的第四十八天,开始了动态规划的强盗问题
198. 打家劫舍
class Solution {
public int rob(int[] nums) {
int n = nums.length;
if(n==1){
return nums[0];
}
int[] dp = new int[n+1];
dp[0] = nums[0];
dp[1] = Math.max(nums[0], nums[1]);
for(int i = 2; i< n; i++){
dp[i] = Math.max(dp[i-1], dp[i-2]+nums[i]);
}
return dp[n-1];
}
}
dp[i]的值要么是不相邻的前一个房子的总值加上现在的,要么可能是之前相邻的房子的值。
213. 打家劫舍2
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;
}
}
要考虑到成环的情况
337. 打家劫舍3
class Solution {
public int rob(TreeNode root) {
int result = steal(root);
return result;
}
public int steal(TreeNode root){
if(root == null){
return 0;
}
int son = steal(root.left);
son += steal(root.right);
if(root.left != null){
if(root.left.left!= null){
root.val += root.left.left.val;
}
if(root.left.right!= null){
root.val += root.left.right.val;
}
}
if(root.right != null){
if(root.right.left!= null){
root.val += root.right.left.val;
}
if(root.right.right!= null){
root.val += root.right.right.val;
}
}
root.val = Math.max(root.val, son);
return root.val;
}
}
不能层序遍历
今天好像是抢劫问题的唯一一天了