给出一个数组,每个数字都是不同的,返回所有的数字组合,使它们的和为target。
每个数字可以重复使用。
思路:
组合问题,用组合版的dfs,因为每个元素可以重复使用,所以下标从当前数字下标 i 开始
如下
dfs(start index, candidates):
for i = i to end
stack.push(candidates[i])
dfs(i, candidates)
stack.pop()
数字和为target,每经过一个元素,令剩下的元素和为target - candidates[i],直到target == 0,则满足和为target。
由于元素可重复使用,所以需要一个终止条件。当元素>target时,认为可以退出,进行下一元素。
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<>();
Stack<Integer> stack = new Stack<>();
dfs(candidates, target, 0, stack, result);
return result;
}
void dfs(int[] candidates, int target, int start, Stack<Integer> stack, List<List<Integer>> result) {
if(target == 0) {
result.add(new ArrayList<Integer>(stack));
return;
}
for(int i = start; i < candidates.length; i ++) {
if(candidates[i] > target) continue;
stack.push(candidates[i]);
dfs(candidates, target - candidates[i], i, stack, result);
stack.pop();
}
}
也可以先把数组排序,当某个元素>target时,后面的必然更大,都不用看了,直接return。
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
int n = candidates.length;
Stack<Integer> cur = new Stack<>();
Arrays.sort(candidates);
combination(candidates, 0, target, result, cur);
return result;
}
public void combination(int[] candidates, int start, int target, List<List<Integer>> result, Stack<Integer> cur) {
if(target < 0) {
return;
}
if(target == 0) {
result.add(new ArrayList<Integer>(cur));
return;
}
for(int i = start; i < candidates.length; i++) {
if(candidates[i] > target) {
break;
}
cur.push(candidates[i]);
combination(candidates, i, target - candidates[i], result, cur);
cur.pop();
}
}