【leetcode刷题笔记】Combination Sum II

时间:2024-12-10 11:05:01

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

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

Note:

  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • The solution set must not contain duplicate combinations.

For example, given candidate set 10,1,2,7,6,1,5 and target 8
A solution set is: 
[1, 7] 
[1, 2, 5] 
[2, 6] 
[1, 1, 6]


Combination Sum的差别就是上面红色的那行字,只要把递归时候的起点由i改为i+1即可,参见下列代码中高亮的部分:

代码如下:

 public class Solution {
private void combiDfs(int[] candidates,int target,List<List<Integer>> answer,List<Integer> numbers,int start){
if(target == 0){
answer.add(new ArrayList<Integer>(numbers));
return;
} int prev = -1; for(int i = start;i < candidates.length;i++){
if(candidates[i] > target)
break;
if(prev != -1 && prev == candidates[i])
continue; numbers.add(candidates[i]);
combiDfs(candidates, target-candidates[i], answer, numbers,i+1);
numbers.remove(numbers.size()-1); prev = candidates[i];
}
}
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> answer = new ArrayList<List<Integer>>();
List<Integer> numbers = new ArrayList<Integer>();
Arrays.sort(candidates);
combiDfs(candidates, target, answer, numbers,0); return answer; }
}