题目描述
给你一个 无重复元素 的整数数组 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,3,5], target = 8
输出: [[2,2,2,2],[2,3,3],[3,5]]
示例 3:
输入: candidates = [2], target = 1
输出: []
提示:
1 <= candidates.length <= 30
2 <= candidates[i] <= 40
candidates
的所有元素 互不相同1 <= target <= 40
解题方法
dfs
跟37题和38题一样,这道题也是dfs。接下来梳理下思路吧。
这道题的关键是什么情况下进行dfs。由题目可知数组都是正数,且元素互不相同。这样我们每加一个数字,数字之和就会越接近target
。
由于数组一开始是无序的,所有我们需要先给数组排序,不然每次dfs都要遍历所有数组,以防错过有效数字。当数组有序后,我们就可以写剪枝条件减少时间复杂度了。
在数组有序之后,我们每次dfs时,记录一下当前参与计算的数字集合和数字之和。当数字之和等于target
时,记录结果集,跳出当前dfs;当数字之和大于target
时,直接跳出当前dfs;当数字之和小于target,继续dfs,不过下一次的dfs起始位置为当前遍历的数组位置。
具体dfs逻辑参考以下代码。
java代码
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(candidates);
List<Integer> curNums = new ArrayList<>();
dfs(candidates, target, result, curNums, 0, 0);
return result;
}
/**
* @param candidates 从小到大排序后的候选数组
* @param target 目标值
* @param result 结果集集合,是个引用
* @param curNums 当前参与计算的数字集合
* @param curSum 当前参与计算的数字之和
* @param start dfs遍历数组开始的位置
*/
public void dfs(int[] candidates, int target, List<List<Integer>> result, List<Integer> curNums, int curSum, int start) {
for (int i = start; i < candidates.length; i++) {
// 当前参与计算的数字之和等于target,添加结果集,并跳出当前dfs
if (curSum + candidates[i] == target) {
curNums.add(candidates[i]);
// 添加结果集的时候需要再new一个list,不然会添加引用,引用会不断变化。
result.add(new ArrayList<>(curNums));
curNums.remove(curNums.size() - 1);
return;
}
// 当前参与计算的数字之和大于target,直接跳出当前dfs(因为数组都是正数,所以不会越加越小)
if (curSum + candidates[i] > target) {
return;
}
// 当前参与计算的数字之和小于target,继续dfs,不过下一次的dfs起始位置start为i
curNums.add(candidates[i]);
dfs(candidates, target, result, curNums, curSum + candidates[i], i);
curNums.remove(curNums.size() - 1);
}
}
复杂度分析
时间复杂度:
O
(
1
)
O(1)
O(1),dfs最大深数为40,每次dfs遍历数组长度最大为30,30 * 40为常数级别。
空间复杂度:
O
(
1
)
O(1)
O(1),dfs最大深度为40,递归调用的存储空间是常数级别。
相似题目
[leetcode] 17. 电话号码的字母组合
[leetcode] 22. 括号生成
[leetcode] 37. 解数独
[leetcode] 38. 外观数列
[leetcode] 40. 组合总和 II
- 个人公众号
- 个人小游戏