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     }
View Code
复制代码

 

posted on   二十年后20  阅读(161)  评论(0编辑  收藏  举报

编辑推荐:
· 对象命名为何需要避免'-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% 的准确率
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示