Combination Sum II

Question

  1. Given a collection of candidate numbers (C) and a target number (T),
  2. find all unique combinations in C where the candidate numbers sums to T.
  3. Each number in C may only be used once in the combination.
  4. Have you met this question in a real interview? Yes
  5. Example
  6. For example, given candidate set 10,1,6,7,2,1,5 and target 8,
  7. A solution set is:
  8. [1,7]
  9. [1,2,5]
  10. [2,6]
  11. [1,1,6]
  12. Note
  13. All numbers (including target) will be positive integers.
  14. Elements in a combination (a1, a2, , ak) must be in non-descending order.
  15. (ie, a1 a2 ak).
  16. The solution set must not contain duplicate combinations.

题解

Unique Subsets 非常类似。在 Combination Sum 的基础上改改就好了。

Java

  1. public class Solution {
  2. /**
  3. * @param num: Given the candidate numbers
  4. * @param target: Given the target number
  5. * @return: All the combinations that sum to target
  6. */
  7. public List<List<Integer>> combinationSum2(int[] num, int target) {
  8. List<List<Integer>> result = new ArrayList<List<Integer>>();
  9. List<Integer> list = new ArrayList<Integer>();
  10. if (num == null) return result;
  11. Arrays.sort(num);
  12. helper(num, 0, target, list, result);
  13. return result;
  14. }
  15. private void helper(int[] nums, int pos, int gap,
  16. List<Integer> list, List<List<Integer>> result) {
  17. if (gap == 0) {
  18. result.add(new ArrayList<Integer>(list));
  19. return;
  20. }
  21. for (int i = pos; i < nums.length; i++) {
  22. // ensure only the first same num is chosen, remove duplicate list
  23. if (i != pos && nums[i] == nums[i - 1]) {
  24. continue;
  25. }
  26. // cut invalid num
  27. if (gap < nums[i]) {
  28. return;
  29. }
  30. list.add(nums[i]);
  31. // i + 1 ==> only be used once
  32. helper(nums, i + 1, gap - nums[i], list, result);
  33. list.remove(list.size() - 1);
  34. }
  35. }
  36. }

源码分析

这里去重的方法继承了 Unique Subsets 中的做法,当然也可以新建一变量 prev,由于这里每个数最多只能使用一次,故递归时索引变量传i + 1.

复杂度分析

时间复杂度 O(n), 空间复杂度 O(n).