运用深搜和栈和递归,代码如下
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
vector<vector<int>> res;
vector<int> path;
DFS(res, candidates, 0, 0, target, path);
return res;
}
void DFS(vector<vector<int>> &res,vector<int>& candidates,int pos,int sum,int target,vector<int>& path) {
if (sum >= target) {
if (sum == target) {
res.push_back(path);
}
else
{
return;
}
}
for (int i = pos; i < candidates.size(); i++) {
//去掉不同位置但是值相同的元素,进两个相同值的元素入栈后等于target 就会一起被存入到res导致重复
if (i != pos&&candidates[i] == candidates[i - 1])continue;
path.push_back(candidates[i]);
DFS(res, candidates, i + 1, sum + candidates[i], target, path);
path.pop_back();
}
}
};
//测试
int main() {
/*
Solution sa ;
vector <int> a;
for (int i = 99; i > 0; i -= 2) {
a.push_back(i);
}
vector<int> k;
for (auto val : a) {
cout << val << ",";
}
cout << "\n\n\n\n";
k=sa.permuteUnique(a);
for (auto val : k) {
cout << val << ",";
}
getchar();*/
Solution sb;
vector<vector<int>> sssa;
vector<int> a;
a.push_back(10);
a.push_back(1);
a.push_back(2);
a.push_back(7);
a.push_back(6);
a.push_back(1);
a.push_back(5);
sssa = sb.combinationSum(a, 8);
for (auto c : sssa) {
for (size_t i = 0; i < c.size(); i++)
{
cout << c[i] << ",";
}
cout << endl;
}
getchar();
}