30 Day Challenge Day 14 | Leetcode 216. Combination Sum III
题解
Medium | Backtracking
class Solution {
public:
vector<vector<int>> combinationSum3(int k, int n) {
vector<vector<int>> sols;
vector<int> sol;
helper(n, k, 1, 0, sol, sols);
return sols;
}
void helper(int n, int k, int index, int sum, vector<int>& sol, vector<vector<int>>& sols) {
if(k == 0) {
if(sum == n) sols.push_back(sol);
return;
}
if(sum > n) return;
for(int i = index; i <= 9; i++) {
sol.push_back(i);
sum += i;
helper(n, k-1, i+1, sum, sol, sols);
sum -= i;
sol.pop_back();
}
}
};