-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution_40.cpp
59 lines (49 loc) · 1.71 KB
/
Solution_40.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
//
// Created by houmo on 19-4-19.
//
#include "Solution_40.h"
vector<vector<int>> Solution_40::combinationSum2(vector<int> &candidates, int target) {
sort(candidates.begin(), candidates.end());
vector<vector<int>> answer;
vector<int>::iterator iter = find(candidates.begin(), candidates.end(), target);
if(iter != candidates.end()){
answer.push_back({target});
candidates.erase(iter);
}
if(target > candidates[0]){
int index = 0;
while(index<candidates.size() && candidates[index] < target){
vector<int> tempCandidates(candidates);
tempCandidates.erase(tempCandidates.begin()+index);
vector<vector<int>> queueAnswer = combinationSum2(tempCandidates, target-candidates[index]);
if(!queueAnswer.empty()){
for(int i=0;i<queueAnswer.size();i++){
vector<int> temp = queueAnswer[i];
temp.push_back(candidates[index]);
sort(temp.begin(), temp.end());
answer.push_back(temp);
}
}
index++;
}
}
if(!answer.empty()){
for(int k=1; k<answer.size(); k++){
for(int n=0; n<k; n++){
if(answer[n].size() == answer[k].size()){
int j;
for(j=0; j<answer[n].size(); j++){
if(answer[n][j] != answer[k][j]){
break;
}
}
if(j>=answer[n].size()){
answer.erase(answer.begin()+k);
k--;
}
}
}
}
}
return answer;
}