39.组合总和

给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。

candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。

对于给定的输入,保证和为 target 的不同组合数少于 150 个。

示例 1:

1
2
3
4
5
6
输入:candidates = [2,3,6,7], target = 7
输出:[[2,2,3],[7]]
解释:
23 可以形成一组候选,2 + 2 + 3 = 7 。注意 2 可以使用多次。
7 也是一个候选, 7 = 7
仅有这两种组合。

示例 2:

1
2
输入: candidates = [2,3,5], target = 8
输出: [[2,2,2,2],[2,3,3],[3,5]]

Solution

选择角度

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
// 用于存储所有可能的组合结果的列表
private final List<List<Integer>> ans = new ArrayList<>();
// 用于存储当前路径的列表
private final List<Integer> path = new ArrayList<>();

// 主要方法,寻找所有可以组成目标值 target 的组合
public List<List<Integer>> combinationSum(int[] candidates, int target) {
// 开始深度优先搜索,初始状态为索引 0 和目标值 target
dfs(0, target, candidates);
return ans;
}

// 深度优先搜索方法
public void dfs(int i, int t, int[] candidates) {
// 如果索引 i 到达数组末尾或目标值 t 小于 0,结束搜索
if (i == candidates.length || t < 0) {
return;
}
// 如果目标值 t 等于 0,找到一个合法组合,将其添加到结果列表中
if (t == 0) {
ans.add(new ArrayList<>(path));
return;
}
// 跳过当前数字,继续搜索下一个数字
dfs(i + 1, t, candidates);
// 选择当前数字,添加到路径中
path.add(candidates[i]);
// 继续搜索当前数字,目标值减少当前数字的值
dfs(i, t - candidates[i], candidates);
// 回溯,移除当前数字
path.remove(path.size() - 1);
}
}

答案角度:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution {
// 用于存储所有可能的组合结果的列表
private final List<List<Integer>> ans = new ArrayList<>();
// 用于存储当前路径的列表
private final List<Integer> path = new ArrayList<>();

// 主要方法,寻找所有可以组成目标值 target 的组合
public List<List<Integer>> combinationSum(int[] candidates, int target) {
// 开始深度优先搜索,初始状态为索引 0 和目标值 target
dfs(0, target, candidates);
return ans;
}

// 深度优先搜索方法
public void dfs(int i, int t, int[] candidates) {
// 如果索引 i 到达数组末尾或目标值 t 小于 0,结束搜索
if (i == candidates.length || t < 0) {
return;
}
// 如果目标值 t 等于 0,找到一个合法组合,将其添加到结果列表中
if (t == 0) {
ans.add(new ArrayList<>(path));
return;
}

// 遍历候选数组,从索引 i 开始
for (int j = i; j < candidates.length; j++) {
// 选择当前数字,添加到路径中
path.add(candidates[j]);
// 继续搜索当前数字,目标值减少当前数字的值
dfs(j, t - candidates[j], candidates);
// 回溯,移除当前数字
path.remove(path.size() - 1);
}
}
}