一、题目
给定一个无重复元素的数组 candidates
和一个目标数 target
,找出 candidates
中所有可以使数字和为 target
的组合。
candidates
中的数字可以无限制重复被选取。
说明: 所有数字(包括 target)都是正整数。 解集不能包含重复的组合。
点击查看原题
难度级别: 中等
二、思路
1)回溯法
由于同一数字可以被无限制重复选取,求和不需要管顺序,那么可以使用从前往后遍历数组的办法,每遍历一个数就是更深一层的搜索,记录遍历路径和遍历路径值的总和,将该题看作多叉树的深度搜索
三、代码
1)回溯法
class Solution {
List<List<Integer>> ans;
public List<List<Integer>> combinationSum(int[] candidates, int target) {
ans = new ArrayList();
List<Integer> temp = new ArrayList();
dfs(candidates, target, temp, 0, 0);
return ans;
}
private void dfs(int[] candidates, int target, List<Integer> temp, int loc, int val) {
if (val > target) {
return;
}
if (target == val) {
ans.add(new ArrayList<Integer>(temp));
return ;
}
for (int i = loc; i < candidates.length; i++) {
temp.add(candidates[i]);
dfs(candidates, target, temp, i, val + candidates[i]);
temp.remove(temp.size()-1);
}
}
}
s
为所有可行解长度之和,时间复杂度为O(s)
,空间复杂度为O(target)