LeetCode: Combination Sum II

本文详细解析了一种组合求和算法,旨在寻找候选数字集合中所有唯一组合,这些组合的总和等于目标数字。通过使用深度优先搜索(DFS)策略,并预先对输入数组进行排序来避免重复解,实现了高效求解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

Each number in C may only be used once in the combination.

这里数字不需要重复出现,所以使用dfs的时候,循环从上一次的下一个位置开始就可以了。

但是这样会出现重复的结果。比如[1,2,3,1],因为第一个位置可以选两次1,所以可能会出现重复结果。

所以这里排序是为了方便避免重复的结果。[1,1,2,3],当为第一个位置选择时,就不必要选两次1了。

 1 public static ArrayList<ArrayList<Integer>> combinationSum2(int[] candidates, int target) {
 2         Arrays.sort(candidates);
 3         ArrayList<Integer> tmp = new ArrayList<Integer>();
 4         ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
 5         process(candidates, 0, tmp, result, 0, target);
 6         return result;
 7     }
 8     
 9     public static void process(int[] candidates, int start, ArrayList<Integer> tmp, ArrayList<ArrayList<Integer>> result,
10             int sum, int target) {
11         if (sum == target) {
12             result.add(new ArrayList<Integer>(tmp));
13             return;
14         }
15         else if (sum < target) {
16             for (int i=start; i<candidates.length; i++) {
17                 tmp.add(candidates[i]);
18                 process(candidates, i+1, tmp, result, sum+candidates[i], target);
19                 tmp.remove(tmp.size()-1);
20                 while(i<candidates.length-1 && candidates[i] == candidates[i+1]) i++;
21             }
22         }
23     }

 

转载于:https://www.cnblogs.com/longhorn/p/3537548.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值