携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第4天,点击查看活动详情 >>
一、题目leetcode39.组合总和
有无重复元素的整数数组 candidates 和一个目标整数 target ,从 candidates 中找出可以使数字和为目标值 target 的所有不同组合 ,并以列表形式返回。可以按任意顺序返回。
candidates 中同一个数字可以使用多次 。如果至少一个数字的被选数量不同,则两种组合是不同的。
对于给定的输入,保证和为 target 的不同组合数少于 150 个。
示例1.
输入:candidates = [2,3,6,7], target = 7
输出:[[2,2,3],[7]]
解释:
2 和 3 可以形成一组候选,2 + 2 + 3 = 7 。注意 2 可以使用多次。
7 也是一个候选, 7 = 7 。
仅有这两种组合。
示例2.
输入: candidates = [2], target = 1
输出: []
二、思路分析
1.由于本题需要找出所有符合要求的组合,并且数字可以无限重复,所以可以穷举所有组合,既使用dfs深度优先搜索。
2.由于选择 candidates 数组中的数时不受限制,所以我们可以跳过不选也可以选,既如果用 i 表示当前candidates数组的第 i 位,则递归函数可以定义为 dfs(target,combine,i),其中 target 表示还需要拼凑得数,combine 表示已经选择的数的集合。dfs(target,combine,i+1) 表示不选择第 i 个数,dfs(target,combine,i) 表示选择第 i 个数。而递归的终止条件为 target <= 0。
三、代码
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> ans = new ArrayList<List<Integer>>();
List<Integer> combine = new ArrayList<Integer>();
dfs(candidates, target, ans, combine, 0);
return ans;
}
private void dfs(int[] candidates, int target, List<List<Integer>> ans, List<Integer> combine, int i) {
if (i == candidates.length){
return;
}
if (target == 0){
ans.add(new ArrayList<>(combine));
return;
}
dfs(candidates, target, ans, combine, i+1);
if(target - candidates[i] >= 0){
combine.add(candidates[i]);
dfs(candidates, target - candidates[i], ans, combine, i);
combine.remove(combine.size() - 1);
}
}
四、总结
本题使用暴力穷举法,通过递归得到最终解集,其时间复杂度为 O(S) 其中 S 为解集中解的个数;空间复杂度为 O(target) 其中 target 表示递归的深度。