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] 

这题和Combination Sum一样,唯一的区别是每个元素只能用一次,而且如果元素里如果有同样的,则都可以用,比如 ([1,1], 2),输出[1],[1]

public class Solution {
  public List<List<Integer>> combinationSum2(int[] candidates, int target) {
    List<List<Integer>> result = new ArrayList<>();
    if (candidates == null || candidates.length == 0) {
      return result;
    }
    Arrays.sort(candidates);
    helper(candidates, 0, target, new ArrayList<>(), result);
    return result;
  }

  public void helper(int[] candidates, int offset, int target, List<Integer> tmp, List<List<Integer>> result) {
    if (target < 0) {
      return;
    }
    if (target == 0) {
      result.add(new ArrayList<Integer>(tmp));
      return;
    }
    for (int i = offset; i < candidates.length; i++) {
      if (i > offset && candidates[i] == candidates[i-1]) {
        continue;
      }
      tmp.add(candidates[i]);
      helper(candidates, i + 1, target - candidates[i], tmp, result);
      tmp.remove(tmp.size() - 1);
    }
  }
}

 

posted on 2015-06-05 07:34  shini  阅读(103)  评论(0编辑  收藏  举报

导航