because T(n) = nT(n - 1) + k
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(result, new ArrayList<Integer>(), 0, candidates, target, 0);
return result;
}
private void helper(List<List<Integer>> result, List<Integer> path, int sum, int[] candidates, int target, int start) {
if (sum == target) {
result.add(new ArrayList<Integer>(path));
return;
}
for (int i = 0; i < candidates.length; i++) {
if (start > 1 && start - 1 > i) {
continue;
}
if (sum + candidates[i] <= target) {
path.add(candidates[i]);
helper(result, path, sum + candidates[i], candidates, target, i + 1);
path.remove(path.size() - 1);
} else {
break;
}
}
}
}
没有评论:
发表评论