class Solution {
public:
vector<int> path;
vector<vector<int>> res;
int sum = 0;
void backtrack(vector<int>& candidates, int target, int startIndex)
{
if (sum >= target)
{
if (sum == target)
{
res.push_back(path);
}
return;
}
else
{
for (int i = startIndex; i < candidates.size() && sum + candidates[i] <= target; i++)
{
path.push_back(candidates[i]);
sum += candidates[i];
backtrack(candidates, target, i);
sum -= path.back();
path.pop_back();
}
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
backtrack(candidates, target, 0);
return res;
}
};
LeetCode39.组合总和
最新推荐文章于 2024-07-16 23:06:39 发布