[Leetcode 40]组合数和II Combination Sum II

时间:2024-12-10 09:34:26

【题目】

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

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

Note:

    • All numbers (including target) will be positive integers.
    • The solution set must not contain duplicate combinations.

Example 1:

Input: candidates = [10,1,2,7,6,1,5], target = 8,
A solution set is:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]

Example 2:

Input: candidates = [2,5,2,1,2], target = 5,
A solution set is:
[
  [1,2,2],
  [5]
]

【思路】

回溯,关键在去重:sort后nums[i-1]==nums[i] continue。

1、[Leetcode 78]求子集 Subset https://www.cnblogs.com/inku/p/9976049.html

2、[Leetcode 90]求含有重复数的子集 Subset II https://www.cnblogs.com/inku/p/9976099.html

3、讲解在这: [Leetcode 216]求给定和的数集合 Combination Sum III

4、[Leetcode 39]组合数的和Combination Sum

【代码】

有参考39的思路设置全局变量+两种情况合并。

class Solution {
private static List<List<Integer>> ans ;
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
ans = new ArrayList<>();
fun(new ArrayList<Integer>(),candidates,target,0);
return ans;
}
public void fun(List<Integer> tmp,int[] data, int aim,int flag){
if(aim<=0){
if(aim==0){
ans.add(new ArrayList<>(tmp));
}
return;
}
for(int i=flag;i<data.length;i++){
if(i>flag&&data[i-1]==data[i])
continue
;
tmp.add(data[i]);
fun(tmp,data,aim-data[i],i+1);
tmp.remove(tmp.size()-1);
}
}
}