39.组合总和
给你一个 无重复元素 的整数数组 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 ≤ c a n d i d a t e s . l e n g t h ≤ 30 1 \leq candidates.length \leq 30 1≤candidates.length≤30
- 2 ≤ c a n d i d a t e s [ i ] ≤ 40 2 \leq candidates[i] \leq 40 2≤candidates[i]≤40
candidates
的所有元素 互不相同- 1 ≤ t a r g e t ≤ 40 1 \leq target \leq 40 1≤target≤40
解法一
思路分析:
- 首先得该题为组合问题,所以使用回溯算法进行求解
- 然后根据回溯算法三要素
- 先考虑回溯函数的返回值和参数,因为不需要回溯函数返回数据,所以返回类型为
void
,然后对于递归函数的参数,传递目标和参数,下一层循环七点参数即可 - 考虑回溯函数的结束条件,即当目标和参数为0时,说明找到符合题意的组合,将其记录,并结束本层递归即可
- 考虑递归函数的一般过程,即使用
for
循环遍历数据集合,选取元素,然后继续递归,然后执行回溯即可
- 先考虑回溯函数的返回值和参数,因为不需要回溯函数返回数据,所以返回类型为
- 对于遍历集合元素,可以进行判断,若添加当元素时,已超过目标和,则不用再递归选取新的元素,跳过该元素即可
实现代码如下:
class Solution {
List<List<Integer>> ans = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
backtracking(target, candidates, 0);
return ans;
}
private void backtracking(int target, int[] candidates, int startIndex) {
if (target == 0) {
ans.add(new ArrayList<>(path));
return ;
}
for (int i = startIndex; i < candidates.length; ++ i) {
if (candidates[i] > target) continue; // 若不符合题意 则跳过该数
path.add(candidates[i]); // 选取符合题意元素
backtracking(target-candidates[i], candidates, i);
path.remove(path.size() - 1);
}
}
}
提交结果如下:
解答成功:
执行耗时:1 ms,击败了99.94% 的Java用户
内存消耗:43.7 MB,击败了31.03% 的Java用户
复杂度分析:
- 时间复杂度:
O
(
n
!
)
O(n!)
O(n!),
n
指数组长度 - 空间复杂度:
O
(
l
)
O(l)
O(l),
l
表示需要记录的解的个数