LeetCode39-组合总和

题目链接

英文链接:https://leetcode.com/problems/combination-sum/

中文链接:https://leetcode-cn.com/problems/combination-sum/

题目详述

给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的数字可以无限制重复被选取。

说明:

  • 所有数字(包括 target)都是正整数。
  • 解集不能包含重复的组合。

示例 1:

1
2
3
4
5
6
输入: candidates = [2,3,6,7], target = 7,
所求解集为:
[
[7],
[2,2,3]
]

示例 2:

1
2
3
4
5
6
7
输入: candidates = [2,3,5], target = 8,
所求解集为:
[
[2,2,2,2],
[2,3,3],
[3,5]
]

题目详解

DFS,回溯。

  • 每次尝试把当前元素添加入临时链表中,target 减去当前元素,然后把新的 target 传入下一层。因为元素允许重复使用,故传入的起始位置为当前位置 i。
  • 递归的终止条件是 target < 0target == 0
  • target < 0 不满足条件,剪枝。
  • target == 0 满足条件,将临时结果拷贝一份加入结果集。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class LeetCode_00039 {

public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
dfs(candidates, target, 0, res, new ArrayList<Integer>());
return res;
}

private void dfs(int[] candidates, int target, int s, List<List<Integer>> res, ArrayList<Integer> list) {
if (target < 0) {
return;
}
if (target == 0) {
res.add(new ArrayList<>(list));
return;
}
for (int i = s; i < candidates.length; ++i) {
list.add(candidates[i]);
// 允许重复使用,所以传入下一层的起始参数为 i
dfs(candidates, target - candidates[i], i, res, list);
list.remove(list.size() - 1);
}
}
}