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.
For example, given candidate set 2,3,6,7 and target 7,
A solution set is:[7][2, 2, 3]
Notice
- All numbers (including target) will be positive integers.
- Elements in a combination must be in non-descending order.
- The solution set must not contain duplicate combinations.
Example
given candidate set 2,3,6,7 and target 7,
A solution set is:[7][2, 2, 3]
Solution: Backtracking.
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if(candidates == null || candidates.length == 0) {
return res;
}
Arrays.sort(candidates);
List<Integer> item = new ArrayList<Integer>();
dfs(candidates, target, res, item, 0);
return res;
}
public void dfs(int[] candidates, int target, List<List<Integer>> res, List<Integer> item, int index) {
if(target == 0) {
res.add(new ArrayList<>(item));
return ;
}
if(target < 0) {
return ;
}
for(int i = index; i < candidates.length; i++) {
if(i > index && candidates[i] == candidates[i - 1]) {
continue;
}
item.add(candidates[i]);
dfs(candidates, target - candidates[i], res, item, i);
item.remove(item.size() - 1);
}
}