40.Combination Sum II
题目链接:https://leetcode.com/problems/combination-sum-ii/description/
题目大意:与39题类似,只是这里数组中的数字可以有重复,且每一个数字只能取一次。
法一:利用39题的剪枝代码,加了一个去重的操作(与前面47和90的去重操作一样)。代码如下(耗时27ms):

1 public List<List<Integer>> combinationSum2(int[] candidates, int target) { 2 List<List<Integer>> res = new ArrayList<List<Integer>>(); 3 List<Integer> tmp = new ArrayList<Integer>(); 4 Arrays.sort(candidates);//先进行排序 5 dfs(res, tmp, candidates, target, 0); 6 return res; 7 } 8 public static boolean dfs(List<List<Integer>> res, List<Integer> tmp, int[] candidates, int target, int start) { 9 if(target < 0) { 10 return false; 11 } 12 if(target == 0) {//递归结束条件 13 res.add(new ArrayList<Integer>(tmp)); 14 return false; 15 } 16 else {//这里一定要判断target>0,因为如果不判断就会导致target<0时还在往下递归 17 for(int i = start; i < candidates.length; i++) { 18 //去重 19 if(i > start && candidates[i] == candidates[i - 1]) { 20 continue; 21 } 22 tmp.add(candidates[i]); 23 boolean flag = dfs(res, tmp, candidates, target - candidates[i], i + 1);//这里是i,因为不能重复选 24 tmp.remove(tmp.size() - 1); 25 //剪枝,因为数组是排好序的,所以一旦总和<=0,那么其后的数字一定会导致当前结果<0,所以可以直接从此跳过后面的循环 26 if(flag == false) { 27 break; 28 } 29 } 30 } 31 return true; 32 }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 对象命名为何需要避免'-er'和'-or'后缀
· SQL Server如何跟踪自动统计信息更新?
· AI与.NET技术实操系列:使用Catalyst进行自然语言处理
· 分享一个我遇到过的“量子力学”级别的BUG。
· Linux系列:如何调试 malloc 的底层源码
· C# 中比较实用的关键字,基础高频面试题!
· .NET 10 Preview 2 增强了 Blazor 和.NET MAUI
· Ollama系列05:Ollama API 使用指南
· 为什么AI教师难以实现
· 如何让低于1B参数的小型语言模型实现 100% 的准确率