40. 组合总和 II(中等)

1,问题描述

40. 组合总和 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,1,6],
[1,2,5],
[1,7],
[2,6]
]

示例 2:

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

提示:

  • 1 <= candidates.length <= 100
  • 1 <= candidates[i] <= 50
  • 1 <= target <= 30

2,初步思考

​ 其本质与39题是一样的,只是多了一个条件只能使用一次数组中的元素

​ 参考39题直接加上限制条件基本就好了

3,代码处理

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import java.util.*;

public class _40组合总和II {

List<int[]> freq = new ArrayList<int[]>();
List<List<Integer>> ans = new ArrayList<List<Integer>>();
List<Integer> sequence = new ArrayList<Integer>();

public List<List<Integer>> combinationSum2_gov(int[] candidates, int target) {
Arrays.sort(candidates);
for (int num : candidates) {
int size = freq.size();
if (freq.isEmpty() || num != freq.get(size - 1)[0]) {
freq.add(new int[]{num, 1});
} else {
++freq.get(size - 1)[1];
}
}
dfs(0, target);
return ans;
}

public void dfs(int pos, int rest) {
if (rest == 0) {
ans.add(new ArrayList<Integer>(sequence));
return;
}
if (pos == freq.size() || rest < freq.get(pos)[0]) {
return;
}

dfs(pos + 1, rest);

int most = Math.min(rest / freq.get(pos)[0], freq.get(pos)[1]);
for (int i = 1; i <= most; ++i) {
sequence.add(freq.get(pos)[0]);
dfs(pos + 1, rest - i * freq.get(pos)[0]);
}
for (int i = 1; i <= most; ++i) {
sequence.remove(sequence.size() - 1);
}
}

// 解法:排序+回溯
public List<List<Integer>> combinationSum2_lookback(int[] candidates, int target) {
Arrays.sort(candidates);
List<List<Integer>> res = new ArrayList<>();
dfs(candidates, target, -1, new ArrayList<>(), res);
return res;
}

private void dfs(int[] candidates, int target, int idx, List<Integer> list, List<List<Integer>> res) {
if (target == 0) {
res.add(new ArrayList<>(list));
return;
}

for (int i = idx + 1; i < candidates.length; i++) {
int nextTarget = target - candidates[i];
if (nextTarget < 0) return;// 剪枝,后面的没必要计算了
if (i != idx + 1 && candidates[i - 1] == candidates[i]) {
continue;
}
list.addLast(candidates[i]);
dfs(candidates, target - candidates[i], i, list, res);
list.removeLast();
}
}

public static void main(String[] args) {
_40组合总和II combinationSum2 = new _40组合总和II();
System.out.println(combinationSum2.combinationSum2(new int[]{10, 1, 2, 7, 6, 1, 5}, 8));
System.out.println(combinationSum2.combinationSum2_lookback(new int[]{10, 1, 2, 7, 6, 1, 5}, 8));
}
}
/**
* 1,1,6
* 1,2,5
* 1,7
* 2,6
*/