代码随想录训练营第四十八天 | 动态规划
今天是训练营的第四十八天,开始了动态规划的强盗问题
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]的值要么是不相邻的前一个房子的总值加上现在的,要么可能是之前相邻的房子的值。
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; } }
要考虑到成环的情况
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; } }
不能层序遍历
今天好像是抢劫问题的唯一一天了
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?