216.组合总和III
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> combinationSum3(int k, int n) {
getSum(k , n , 1, 0);
return res;
}
public void getSum(int k , int targetSum, int startindex, int sum){
if(path.size() == k){
if(targetSum == sum)
res.add(new ArrayList(path));
return;
}
for(int i = startindex; i <= 9 ; i++){
sum += i;
path.add(i);
getSum(k , targetSum , i + 1 , sum);
sum -= i;
path.remove(path.size() - 1);
}
}
}
这个也可以剪枝,通过将 i <= 9 改为 i <= 9 - (path.size() - k) +1
实际跟上一题做法相似。