class Solution {
private:
vector<int> c;
vector<vector<int> > res; //保存最后结果
public:
vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
vector<int> a;
sort(candidates.begin(), candidates.end()); //先对C中候选数升序排序,为后面的剪枝做准备
c = candidates;
backtrack(a, 0, target);
//for(vector<int> &m:res)
//sort(m.begin(), m.end());
//res.erase(unique(res.begin(), res.end()), res.end());
return res;
}
int sum(vector<int>& a){
int res = 0;
for (int i = 0; i<a.size(); i++){
res += a[i];
}
return res;
};
void backtrack(vector<int>& a, int k, int target)
{
if (k == c.size()) return;
if (sum(a) == target){
res.push_back(a);
return;
}
else if (sum(a)>target)
return;
else {
//k = k + 1;
for (int i = k; i<c.size(); i++) {
//a[k] = c[i];
a.push_back(c[i]);
backtrack(a, i, target);
a.pop_back();
}
}
}
};
转载于:https://www.cnblogs.com/muyangshaonian/p/9650496.html