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]
Source
public class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> st = new ArrayList<List<Integer>>();
List<Integer> a = new ArrayList<Integer>();
if(candidates.length == 0) return st;
int sum = 0;
int start = 0;
Arrays.sort(candidates); //这道题的测试数据有乱序的
dfs(start, sum, candidates, target, st, a);
return st;
}
public void dfs(int start, int sum, int[] candidates, int target, List<List<Integer>> st, List<Integer> a){
if(sum > target) return;
if(sum == target){
st.add(new ArrayList<Integer>(a));
return;
}
for(int i = start; i < candidates.length; i++){
a.add(candidates[i]);
dfs(i, sum + candidates[i], candidates, target, st, a); //注意sum是要随着dfs变化的
a.remove(a.size() - 1);
}
}
}
Test
public static void main(String[] args){
int[] candidates = {2,3,6,7};
int target = 7;
System.out.println(new Solution().combinationSum(candidates, target));
}