组合总和Ⅲ

216. 组合总和 III

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

  • 只使用数字1到9
  • 每个数字 最多使用一次

返回 所有可能的有效组合的列表 。该列表不能包含相同的组合两次,组合可以以任何顺序返回。

示例 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,没有有效的组合。

提示:

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

image-20230811100937307

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
List<List<Integer>> ans = new ArrayList<>();
List<Integer> path = new ArrayList<>();

public List<List<Integer>> combinationSum3(int k, int n) {
traversal(k,n,0,1);
return ans;
}

public void traversal(int k, int n, int sum, int startIndex){
if(path.size() == k){
if(sum == n){
ans.add(new ArrayList<>(path));
}
return;
}

for(int i = startIndex; i <= 9; i++){
path.add(i);
traversal(k, n, sum+i, i+1);
path.remove(path.size()-1);
}
}
}
  • 时间复杂度: $O(n * 2^n)$ :n为集合的大小,本题中n为9,每个数有两种状态,选或不选
  • 空间复杂度: $O(n)$

剪枝优化

如果当前的sum已经大于目标值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
class Solution {
List<List<Integer>> ans = new ArrayList<>();
List<Integer> path = new ArrayList<>();

public List<List<Integer>> combinationSum3(int k, int n) {
traversal(k,n,0,1);
return ans;
}

public void traversal(int k, int n, int sum, int startIndex){
if(sum > n || k < path.size()){ //剪枝
return;
}
if(sum == n && k == path.size()){
ans.add(new ArrayList<>(path));
return;
}

for(int i = startIndex; i <= 9; i++){
path.add(i);
traversal(k, n, sum+i, i+1);
path.remove(path.size()-1);
}
}
}

组合总和Ⅲ
http://example.com/2023/04/23/算法/回溯/2. 组合总和 III/
作者
PALE13
发布于
2023年4月23日
许可协议