216. 组合总和 III
难度:中等
2020/9/11每日一题打卡
题目描述
解题思路
也是回溯+剪枝,貌似好像也只要套模板
1 和2都是给定数组,这个是1-9里面选数字,其实也能被看作是数组,每个数字只能被选一次
最后不仅仅要求总和等于给定值,长度也要满足要求
/*
* 216. 组合总和 III
* 2020/9/11
* medium
*/
public List<List<Integer>> combinationSum3(int k, int n) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> temp = new ArrayList<>();
if(k == 0 || n == 0) {
return res;
}
combinationSum3Helper(k,n,res,temp,1,0);
return res;
}
public void combinationSum3Helper(int k,int n,List<List<Integer>> res,List<Integer> temp,int cur,int sum) {
if(temp.size() == k ) {
if(sum == n)
res.add(new ArrayList<>(temp));
return;
}
for (int i = cur; i <= 9; i++) {
if(sum + i <= n) {
sum += i;
temp.add(i);
combinationSum3Helper(k,n,res,temp,i+1,sum);
sum -= i;
temp.remove(temp.size()-1);
}
}
}