2024.4.21
题目来源
我的题解
方法一 回溯
需要在 9个数中选择 k个数,让它们的和为 n。
时间复杂度:O((10−k)!) 。组合问题的时间复杂度
空间复杂度:O(k)。
class Solution {
List<List<Integer>> res;
public List<List<Integer>> combinationSum3(int k, int n) {
res=new ArrayList<>();
List<Integer> path=new ArrayList<>();
for(int i=1;i<=10-k;i++){
path.add(i);
dfs(i,k-1,n,n-i,path);
path.remove(path.size()-1);
}
return res;
}
public void dfs(int index,int k,int n,int target,List<Integer> path){
if(k==0&&target==0){
res.add(new ArrayList<>(path));
}
if(k<0||target<0)
return;
for(int i=index+1;i<=10-k;i++){
path.add(i);
dfs(i,k-1,n,target-i,path);
path.remove(path.size()-1);
}
}
}
方法二 二进制(子集)枚举
这是官方题解的思路
时间复杂度:O( M × 2 M M×2^M M×2M)
空间复杂度:O(M)
class Solution {
List<Integer> temp = new ArrayList<Integer>();
List<List<Integer>> ans = new ArrayList<List<Integer>>();
public List<List<Integer>> combinationSum3(int k, int n) {
for (int mask = 0; mask < (1 << 9); ++mask) {
if (check(mask, k, n)) {
ans.add(new ArrayList<Integer>(temp));
}
}
return ans;
}
public boolean check(int mask, int k, int n) {
temp.clear();
for (int i = 0; i < 9; ++i) {
if (((1 << i) & mask) != 0) {
temp.add(i + 1);
}
}
if (temp.size() != k) {
return false;
}
int sum = 0;
for (int num : temp) {
sum += num;
}
return sum == n;
}
}
有任何问题,欢迎评论区交流,欢迎评论区提供其它解题思路(代码),也可以点个赞支持一下作者哈😄~