LC.39.Combination Sum

https://leetcode.com/problems/combination-sum/description/

Given a set of candidate numbers (C) (without duplicates) 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.
The solution set must not contain duplicate combinations.
For example, given candidate set [2, 3, 6, 7] and target 7,
A solution set is:
[
[7],
[2, 2, 3]
]

time: o(2^n)
space: o(n)

 1 public List<List<Integer>> combinationSum(int[] candidates, int target) {
 2         List<List<Integer>> res = new ArrayList<>();
 3         dfs(candidates, target, 0, res, new ArrayList<>());
 4         return res ;
 5     }
 6     private void dfs(int[] candidates, int remain,int start, List<List<Integer>> res, List<Integer> sol){
 7         //terminate condition
 8         if (remain <= 0) {
 9             if (remain == 0) {
10                 res.add(new ArrayList(sol));
11             }
12             return;
13         }
14         for (int i = start ; i < candidates.length; i++) {
15                sol.add(candidates[i]);
16                //因为允许重复,所以用i
17                dfs(candidates, remain-candidates[i], i, res, sol);
18                sol.remove(sol.size()-1);
19         }
20     }
原文地址:https://www.cnblogs.com/davidnyc/p/8703126.html