leetcode -- 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, � , ak) must be in non-descending order. (ie, a1 ? a2 ? � ? ak).
- 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]
本题是求解所有可能的组合数,可用DFS来求解,如需求解最优解,需使用DP
DFS的递归函数中只处理当前状态节点n,而不关心它的下一状态
1 public class Solution { 2 public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) { 3 // Start typing your Java solution below 4 // DO NOT write main() function 5 int len = candidates.length; 6 ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>(); 7 if(len == 0) 8 return results; 9 10 Arrays.sort(candidates); 11 12 ArrayList<Integer> result = new ArrayList<Integer>(); 13 int level = 0; 14 int sum = 0; 15 DFS(candidates, level, sum, target, result, results); 16 return results; 17 } 18 19 public void DFS(int[] candidates, int level, int sum, int target, ArrayList<Integer> result, 20 ArrayList<ArrayList<Integer>> results){ 21 if(sum > target) 22 return; 23 24 if(sum == target){ 25 ArrayList<Integer> tmp = new ArrayList<Integer>(); 26 tmp.addAll(result); 27 results.add(tmp); 28 return; 29 } 30 if(sum < target){ 31 for(int i = level; i < candidates.length; i++){ 32 sum += candidates[i]; 33 result.add(candidates[i]); 34 DFS(candidates, i, sum, target, result, results); 35 result.remove(result.size() - 1); 36 sum -= candidates[i]; 37 } 38 } 39 } 40 }
ref: