思路,dfs加剪枝,暴力做的勉强过了
class Solution {
public:
stack <int> s;
int tar;
int l;
vector <int> nums;
vector<vector<int>> an;
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
tar = target;
nums = candidates;
l = nums.size();
sort(nums.begin(), nums.end());
for(int i = 0; i < l; i++){
s.push(nums[i]);
dfs(i, nums[i]);
s.pop();
}
return an;
}
void addInAn(){
stack <int> q = s;
vector <int> an1;
while(!q.empty()){
an1.push_back(q.top());
q.pop();
}
int l2 = an.size();
for(int i = 0; i < l2; i++){
if(an[i] == an1){
return;
}
}
an.push_back(an1);
}
void dfs(int place, int nowVal){
if(place >= l){
return;
}
if(nowVal > tar){
return;
}
if(nowVal == tar){
addInAn();
return;
}
for(int i = place + 1; i < l; i++){
s.push(nums[i]);
dfs(i, nowVal + nums[i]);
s.pop();
}
}
};