题目描述
找出所有相加之和为 n 的 k 个数的组合。组合中只允许含有 1 - 9 的正整数,并且每种组合中不存在重复的数字。
说明:
- 所有数字都是正整数。
- 解集不能包含重复的组合。
示例 1:
输入: k = 3, n = 7
输出: [[1,2,4]]
示例 2:
输入: k = 3, n = 9
输出: [[1,2,6], [1,3,5], [2,3,4]]
分析
(DFS) O(Ck9)
暴力搜索出所有从9个数中选k个的方案,记录所有和等于 n
的方案。
为了避免重复计数,比如 {1, 2, 3} 和 {1, 3, 2} 是同一个集合,我们对集合中的数定序,每次枚举时,要保证同一方案中的数严格递增,即如果上一个选的数是 x,那我们从 x+1
开始枚举当前数。
时间复杂度分析:从9个数中选k个总共有 Ck9
个方案,所以时间复杂度是 O(Ck9)。
贴出代码
class Solution {
private List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> combinationSum3(int k, int n) {
dfs(k,n,1,0,new ArrayList<>());
return res;
}
private void dfs(int k, int n,int start,int sum, List<Integer> path){
if(k == 0){
if (sum == n){
res.add(new ArrayList<>(path));
}
return;
}
for (int i = start; i <= 9; i ++){
if (n >= i){
path.add(i);
dfs(k - 1,n ,i + 1,sum + i,path);
path.remove(path.size() - 1);
}
}
}
}