class Solution {
public:
vector<int> path;
vector<vector<int>> res;
int getSum(vector<int> path)
{
int sum = 0;
for (int i = 0; i < path.size(); i++)
sum += path[i];
return sum;
}
void backtrack(int k, int n, int startIndex)
{
if (path.size() == k)
{
if (getSum(path) == n)
res.push_back(path);
return;
}
else
{
for (int i = startIndex; i <= 9; i++)
{
path.push_back(i);
backtrack(k, n, i + 1);
path.pop_back();
}
}
}
vector<vector<int>> combinationSum3(int k, int n) {
backtrack(k, n, 1);
return res;
}
};
LeetCode216.组合总和 III
最新推荐文章于 2024-06-21 17:14:10 发布