Combination Sum

描述

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1,a2,…,aka_1, a_2, …, a_ka​1​​,a​2​​,…,a​k​​) must be in non-descending order. (ie, a1≤a2≤…≤aka_1 \leq a_2 \leq … \leq a_ka​1​​≤a​2​​≤…≤a​k​​).
  • The solution set must not contain duplicate combinations.
    For example, given candidate set 2,3,6,7 and target 7, A solution set is:
  1. [7]
  2. [2, 2, 3]

分析

代码

  1. // Combination Sum
  2. // 时间复杂度O(n!),空间复杂度O(n)
  3. public class Solution {
  4. public List<List<Integer>> combinationSum(int[] nums, int target) {
  5. Arrays.sort(nums);
  6. List<List<Integer>> result = new ArrayList<>(); // 最终结果
  7. List<Integer> path = new ArrayList<>(); // 中间结果
  8. dfs(nums, path, result, target, 0);
  9. return result;
  10. }
  11. private static void dfs(int[] nums, List<Integer> path,
  12. List<List<Integer>> result, int gap, int start) {
  13. if (gap == 0) { // 找到一个合法解
  14. result.add(new ArrayList<Integer>(path));
  15. return;
  16. }
  17. for (int i = start; i < nums.length; i++) { // 扩展状态
  18. if (gap < nums[i]) return; // 剪枝
  19. path.add(nums[i]); // 执行扩展动作
  20. dfs(nums, path, result, gap - nums[i], i);
  21. path.remove(path.size() - 1); // 撤销动作
  22. }
  23. }
  24. }

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/dfs/combination-sum.html