forked from cpselvis/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution040.cpp
More file actions
60 lines (53 loc) · 1.25 KB
/
solution040.cpp
File metadata and controls
60 lines (53 loc) · 1.25 KB
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
60
/**
* Combination Sum II
*
* cpselvis([email protected])
* September 17th, 2016
*/
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
vector<vector<int> > ret;
vector<int> sub;
sort(candidates.begin(), candidates.end());
backtack(candidates, 0, ret, sub, target);
return ret;
}
void backtack(vector<int> &candidates, int index, vector<vector<int> > &ret, vector<int> &sub, int target)
{
if (target == 0)
{
ret.push_back(sub);
}
for (; index < candidates.size() && candidates[index] <= target; index ++)
{
int num = candidates[index];
sub.push_back(num);
backtack(candidates, index + 1, ret, sub, target - num);
sub.pop_back();
// Avoid duplicate situations.
while (index + 1 < candidates.size() && candidates[index] == candidates[index + 1])
{
index ++;
}
}
}
};
int main(int argc, char **argv)
{
int arr[7] = {10, 1, 2, 7, 6, 1, 5};
vector<int> vec(arr + 0, arr + 7);
Solution s;
vector<vector<int> > ret = s.combinationSum2(vec, 8);
for (auto i : ret)
{
for (auto j : i)
{
cout << j << " ";
}
cout << endl;
}
}