标签:
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:
For example, given candidate set 2,3,6,7
and target 7
,
A solution set is: [7]
[2, 2, 3]
public class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<>();
if (candidates == null || candidates.length == 0) {
return result;
}
Arrays.sort(candidates);
helper(candidates, 0, target, new ArrayList<>(), result);
return result;
}
public void helper(int[] candidates, int offset, int target, List<Integer> tmp, List<List<Integer>> result) {
if (target < 0) {
return;
}
if (target == 0) {
result.add(new ArrayList<Integer>(tmp));
return;
}
for (int i = offset; i < candidates.length; i++) {
if (i > 0 && candidates[i] == candidates[i-1]) {
continue;
}
tmp.add(candidates[i]);
helper(candidates, i, target - candidates[i], tmp, result);
tmp.remove(tmp.size() - 1);
}
}
}
标签:
原文地址:http://www.cnblogs.com/shini/p/4553653.html