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.
  • 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. [
  2. [1, 7],
  3. [1, 2, 5],
  4. [2, 6],
  5. [1, 1, 6]
  6. ]

Solution:

  1. public class Solution {
  2. public List<List<Integer>> combinationSum2(int[] candidates, int target) {
  3. Arrays.sort(candidates);
  4. List<List<Integer>> res = new ArrayList<List<Integer>>();
  5. helper(candidates, target, 0, new ArrayList<Integer>(), res);
  6. return res;
  7. }
  8. private void helper(int[] candidates, int target, int index, List<Integer> sol, List<List<Integer>> res) {
  9. if (target == 0) {
  10. res.add(new ArrayList<Integer>(sol));
  11. return;
  12. }
  13. if (target < 0 || index == candidates.length) {
  14. return;
  15. }
  16. for (int i = index; i < candidates.length; i++) {
  17. if (i > index && candidates[i] == candidates[i - 1]) {
  18. continue;
  19. }
  20. sol.add(candidates[i]);
  21. helper(candidates, target - candidates[i], i + 1, sol, res);
  22. sol.remove(sol.size() - 1);
  23. }
  24. }
  25. }