LeetCodeHot100_40——《组合总和Ⅱ》
解题思路:这道题和上一道题总的思路差不多,但是需要注意的是这里边的数字使用次数有了限制。参考思路代码随想录:代码随想录 (programmercarl.com)
具体代码:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
vector<vector<int>> result; //建立一个二维数组,存最后的答案
vector<int> path;//建立一个数组,用来临时存放答案
void backtracking(vector<int>& candidates, int target, int sum, int startIndex) {
if (sum > target)
{
return;
}
if (sum == target)
{
result.push_back(path);
return;
}
for (int i = startIndex; i < candidates.size() && sum+candidates[i] <= target; i++)
{
if (i>startIndex&&candidates[i]==candidates[i-1])
{
continue;
}
sum += candidates[i];
path.push_back(candidates[i]);
backtracking(candidates, target, sum, i+1);
sum -= candidates[i];
path.pop_back();
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
result.clear();
path.clear();
sort(candidates.begin(), candidates.end());
backtracking(candidates, target, 0, 0);
return result;
}
int main() {
vector<int> candidates = { 2,3,5 };
int target = 8;
vector<vector<int>> test = combinationSum(candidates, target);
return 0;
}