class Solution {
public:
vector<vector<int>> combinationSum3(int k, int n)
{
backTracing(k, n, 0, 1);
return result;
}
private:
vector<vector<int>> result;
vector<int> path;
void backTracing(int k, int n, int sum, int startIndex);
};
inline void Solution::backTracing(int k, int n, int sum, int startIndex)
{
if (sum > n)//减少循环都是剪枝
{
return;
}
if (path.size() == k)
{
if (sum == n) result.push_back(path);
return;
}
for (int i = startIndex; i <= (9 - (k - path.size()) + 1); ++i)
{
path.push_back(i);
sum += i;
backTracing(k, n, sum, i + 1);
sum -= i;
path.pop_back();
}
}