Combination Sum

Question

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

题解

Permutations 十分类似,区别在于剪枝函数不同。这里允许一个元素被多次使用,故递归时传入的索引值不自增,而是由 for 循环改变。

Java

  1. public class Solution {
  2. /**
  3. * @param candidates: A list of integers
  4. * @param target:An integer
  5. * @return: A list of lists of integers
  6. */
  7. public List<List<Integer>> combinationSum(int[] candidates, int target) {
  8. List<List<Integer>> result = new ArrayList<List<Integer>>();
  9. List<Integer> list = new ArrayList<Integer>();
  10. if (candidates == null) return result;
  11. Arrays.sort(candidates);
  12. helper(candidates, 0, target, list, result);
  13. return result;
  14. }
  15. private void helper(int[] candidates, int pos, int gap,
  16. List<Integer> list, List<List<Integer>> result) {
  17. if (gap == 0) {
  18. // add new object for result
  19. result.add(new ArrayList<Integer>(list));
  20. return;
  21. }
  22. for (int i = pos; i < candidates.length; i++) {
  23. // cut invalid candidate
  24. if (gap < candidates[i]) {
  25. return;
  26. }
  27. list.add(candidates[i]);
  28. helper(candidates, i, gap - candidates[i], list, result);
  29. list.remove(list.size() - 1);
  30. }
  31. }
  32. }

源码分析

对数组首先进行排序是必须的,递归函数中本应该传入 target 作为入口参数,这里借用了 Soulmachine 的实现,使用 gap 更容易理解。注意在将临时 list 添加至 result 中时需要 new 一个新的对象。

复杂度分析

按状态数进行分析,时间复杂度 O(n!), 使用了list 保存中间结果,空间复杂度 O(n).

Reference

  • Soulmachine 的 leetcode 题解