40. Combination Sum II - jiejackyzhang/leetcode-note GitHub Wiki

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.

Note:

  • All numbers (including target) will be positive integers.
  • 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]
]

解题思路为backtracking。

先将candidates排序,然后对于duplicates只算第一个,因为把含有这个值的情况都考虑了,其他的都跳过,从下一个不同的值开始。

public class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        Arrays.sort(candidates);
        helper(candidates, target, 0, new ArrayList<Integer>(), res);
        return res;
    }
    
    private void helper(int[] candidates, int target, int index, List<Integer> sofar, List<List<Integer>> res) {
        if(target == 0) {
            res.add(new ArrayList<Integer>(sofar));
            return;
        }
        for(int i = index; i < candidates.length; i++) {
            int newTarget = target - candidates[i];
            if(newTarget >= 0) {
                sofar.add(candidates[i]);
                helper(candidates, newTarget, i+1, sofar, res);
                sofar.remove(sofar.size()-1);
            } else {
                break;
            }
            // skip duplicates
            while(i+1 < candidates.length && candidates[i] == candidates[i+1]) i++;
        }
    }
}
⚠️ **GitHub.com Fallback** ⚠️