leetcode组合总和 Ⅳ 解题路径
题目:
关于动态规划类题目的思路如何找在上一篇博客 https://www.cnblogs.com/niuyourou/p/11964842.html 讲的非常清楚了,该博客也成为了了leetcode中戳气球题目点赞和阅读最多的题解(虽然题解本身就很少)。
本题的解题路径与上述博客一致,也是从 递归 到 分治 到 动态规划。
各个解法之间的过渡不再赘述,有兴趣的朋友可以看看我的上述博客。https://www.cnblogs.com/niuyourou/p/11964842.html
这次我们只贴关键代码供各位参考:
递归搜索解法:
/** * @Author Nxy * @Date 2019/12/21 * @Param * @Return * @Exception * @Description 递归搜索 */ int i = 0; public int combinationSum4(int[] nums, int target) { if (nums == null) { return 0; } combinationSum4(nums, 0, target); return i; } public void combinationSum4(int[] nums, int beforeRe, int target) { if (beforeRe > target) { return; } if (beforeRe == target) { i++; return; } int length = nums.length; for (int i = 0; i < length; i++) { int tempRe = beforeRe + nums[i]; combinationSum4(nums, tempRe, target); } }
分治解法:
状态转移方程:dp[i] = sum{ dp[i - num] for num in nums and if i >= num }
/** * @Author Nxy * @Date 2019/12/21 * @Param * @Return * @Exception * @Description 分治加缓存 */ public int combinationSum4II(int[] nums, int target) { if (nums == null) { return 0; } int length = nums.length; Map<Integer, Integer> cache = new HashMap<Integer, Integer>(); return combinationSum4II(nums, target, length, cache); } public int combinationSum4II(int[] nums, int target, int length, Map<Integer, Integer> cache) { if (target < 0) { return 0; } if (target == 0) { return 1; } Set s = cache.keySet(); if (s.contains(target)) { return cache.get(target); } int temp = 0; for (int i = 0; i < length; i++) { temp += combinationSum4II(nums, target - nums[i], length, cache); } cache.put(target, temp); return temp; }
从递归到分治的效率提升:
动态规划解法:
/** * @Author Nxy * @Date 2019/12/21 * @Param * @Return * @Exception * @Description DP解法 */ public int combinationSum4III(int[] nums, int target){ if(nums==null){return 0;} int length=nums.length; int[] cache=new int[target+1]; cache[0]=1; for(int i=1;i<=target;i++){ int temp=0; for(int j=0;j<length;j++){ if(i-nums[j]==0){ temp++; continue; } if(i-nums[j]>0){ temp+=cache[i-nums[j]]; } } cache[i]=temp; } return cache[target]; }
效率提升:
递归太费时,我们单独看下分治到动态规划的效率提升:
当你看清人们的真相,于是你知道了,你可以忍受孤独
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构