LeetCode_80_ComBinationSumII


1. question: 组合总和III(中等)

找出所有相加之和为 n 的 k 个数的组合,且满足下列条件:

  1. 只使用数字1到9
  2. 每个数字 最多使用一次
  3. 返回 所有可能的有效组合的列表 。该列表不能包含相同的组合两次,组合可以以任何顺序返回。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/combination-sum-iii

示例 1:

1
2
3
4
5
输入: k = 3, n = 7
输出: [[1,2,4]]
解释:
1 + 2 + 4 = 7
没有其他符合的组合了。

示例 2:

1
2
3
4
5
6
7
输入: k = 3, n = 9
输出: [[1,2,6], [1,3,5], [2,3,4]]
解释:
1 + 2 + 6 = 9
1 + 3 + 5 = 9
2 + 3 + 4 = 9
没有其他符合的组合了。

示例 3:

1
2
3
4
输入: k = 4, n = 1
输出: []
解释: 不存在有效的组合。
在[1,9]范围内使用4个不同的数字,我们可以得到的最小和是1+2+3+4 = 10,因为10 > 1,没有有效的组合。

提示:

1
2
2 <= k <= 9
1 <= n <= 60

2. answers

这道题和组合是一样的思路。采用回溯法,但是增加了k个数之和为n,最简单的方法就是在组合的基础上,在添加到结果之前,先判断一下,k数之和是否为n,如是,则将其添加到结果中。代码如下所示:

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

public List<List<Integer>> res = new ArrayList<>();
public LinkedList<Integer> path = new LinkedList<>(); // 为了删除结尾的元素,采用链表List

public void recur(int k, int n, int startIndex) {

if(path.size() == k) {

int sum = 0;

for(Integer i: path) sum += i;

if(sum == n) res.add(new ArrayList<>(path));

return;
}


for (int i = startIndex; i <= 9 - (k - path.size()) + 1; i++) {

path.add(i);

// 递归下一个数
recur(k, n, i + 1);

// 撤销上一个满足结果的集合中的最后的数
path.removeLast();
}
}

public List<List<Integer>> combinationSum3(int k, int n) {

recur(k, n, 1);

return res;
}

public static void main(String[] args) {
System.out.println();

Solution_0079 s = new Solution_0079();

List<List<Integer>> result = s.combinationSum3(9, 45);

for(List<Integer> list: result) {

for(Integer i: list)
System.out.print(i + "\t");

System.out.println();
}
}
}

但是,其实可以剪枝,在递归的时候,保留一个变量,累加前面路径之和,如果已经大于n了,则没必要再递归了。代码如下所示:

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
public int sums;

public void recur(int k, int n, int startIndex) {

if(path.size() == k) {
if(sums == n) res.add(new ArrayList<>(path));
return;
}


for (int i = startIndex; i <= 9 - (k - path.size()) + 1; i++) {

path.add(i);

sums += i;

// 如果当前选择已经大于n了,那么就没必要继续遍历了,直接循环下一个选择。
// 注意,将总和sums减去i
if(sums > n) {
path.removeLast();
sums -= i;
continue;
}

// 递归下一个数
recur(k, n, i + 1);

// 撤销上一个满足结果的集合中的最后的数
path.removeLast();
sums -= i; // 注意,要将总和中去掉i
}
}

3. 备注

参考力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台 (leetcode-cn.com)代码随想录 (programmercarl.com)


文章作者: 浮云
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 浮云 !
  目录