LeetCode40-组合总和II

题目链接

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

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

题目详述

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

candidates 中的每个数字在每个组合中只能使用一次。

说明:

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

示例 1:

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

示例 2:

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

题目详解

DFS,回溯。本题与 LeetCode39-组合总和 的区别在于添加了一个不重复的条件,每个元素只能使用一次。在原来的基础上首先排序,跳过重复元素即可。

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
public class LeetCode_00040 {

public List<List<Integer>> combinationSum2(int[] candidates, int target) {
// 首先排序
Arrays.sort(candidates);
List<List<Integer>> res = new ArrayList<>();
dfs(candidates, target, 0, res, new ArrayList<>());
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) {
// 跳过重复
if (i > s && candidates[i] == candidates[i - 1]) {
continue;
}
list.add(candidates[i]);
// 传入下一层的起始参数为 i + 1
dfs(candidates, target - candidates[i], i + 1, res, list);
list.remove(list.size() - 1);
}
}
}