`

LeetCode 40 - Combination Sum II

 
阅读更多

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.
  • 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] 

 

Solution:

注意先排序,保证从小到大。递归终止的条件是:

  1. target值小于0,说明后面不可能有解了。
  2. target值等于0,说明已经找到解。
public List<List<Integer>> combinationSum2(int[] num, int target) {
    List<List<Integer>> result = new ArrayList<>();
    Arrays.sort(num);
    combine(result, new ArrayList<Integer>(), num, target, 0);
    return result;
}

private void combine(List<List<Integer>> result, List<Integer> list, int[] num, int target, int pos) {
    if(target < 0) return;
    if(target == 0) {
        result.add(new ArrayList<Integer>(list));
        return;
    }
    for(int i=pos; i<num.length; i++) {
        if(i>pos && num[i] == num[i-1]) continue;
        list.add(num[i]);
        combine(result, list, num, target-num[i], i+1);
        list.remove(list.size()-1);
    }
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics