LeetCode 39. Combination Sum
Woodyiiiiiii opened this issue · comments
Given a set of candidate numbers (candidates
) (without duplicates) and a target number (target
), find all unique combinations in candidates
where the candidate numbers sums to target
.
The same repeated number may be chosen from candidates
unlimited number of times.
Note:
- All numbers (including
target
) will be positive integers. - The solution set must not contain duplicate combinations.
Example 1:
Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
[7],
[2,2,3]
]
Example 2:
Input: candidates = [2,3,5], target = 8,
A solution set is:
[
[2,2,2,2],
[2,3,3],
[3,5]
]
这道题的常见解法是DFS+回溯,跟做过的permutations, subset等题目一样的思路,主要是要注意递归调用时各个变量的含义就可以了,不再赘述:
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> tmp = new ArrayList<>();
dfs(res, tmp, candidates, target, 0, 0);
return res;
}
public void dfs(List<List<Integer>> res, List<Integer> tmp,
int[] candidates, int target, int sum, int level) {
if (sum > target) return;
else if (sum == target) {
res.add(new ArrayList<>(tmp));
return;
}
for (int i = level; i < candidates.length; ++i) {
tmp.add(candidates[i]);
sum += candidates[i];
dfs(res, tmp, candidates, target, sum, i);
sum -= tmp.get(tmp.size() - 1);
tmp.remove(tmp.size() - 1);
}
}
}
第二种递归写法是不用sum这个变量来计算,直接将target减去相应的值作为参数传递:
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> tmp = new ArrayList<>();
dfs(0, res, tmp, candidates, target);
return res;
}
public void dfs(int level, List<List<Integer>> res, List<Integer> tmp,
int[] candidates, int target){
if (target < 0) return;
if (target == 0) {
res.add(new ArrayList<>(tmp));
return;
}
for(int i = level ; i < candidates.length ; ++i){
tmp.add(candidates[i]);
dfs(i, res, tmp, candidates, target - candidates[i] );
tmp.remove(tmp.size()-1);
}
}
}
此外可以将List类型的tmp变量改位Stack类,会发现运行时间会小很多。
参考资料: