-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path39_CombinationSum.cpp
96 lines (88 loc) · 1.63 KB
/
39_CombinationSum.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include<string>
#include <set>
#include<iostream>
#include<map>
#include<unordered_map>
#include<algorithm>
#include<stack>
#include<unordered_set>
#include <iterator>
#include<vector>
using namespace std;
vector<vector<int>> combinationSum(vector<int>& candidates, int target)
{
vector<vector<int>> result;
int length = candidates.size();
int sum = 0;
vector<int> subResult;
for (int i = 0; i < length; ++i)
{
if (candidates[i] == target)
{
result.push_back({ candidates[i] });
continue;
}
//case: when array sum is eqaul to target.
sum += candidates[i];
subResult.push_back(candidates[i]);
if (sum == target)
{
result.push_back(subResult);
subResult.clear();
continue;
}
if (sum > target)
{
sum = candidates[i];
subResult.clear();
subResult.push_back(candidates[i]);
}
//check if current number itself adds up to the target
int num = candidates[i];
vector<int> r2;
r2.push_back(candidates[i]);
while (1)
{
if (num == target)
{
//r2.push_back(candidates[i]);
result.push_back(r2);
}
if (num < target)
{
r2.push_back(candidates[i]);
}
else
{
break;
}
num += candidates[i];
}
vector<int> r1(subResult);
int j = i;
while (j >= 0)
{
int newNumber = sum + candidates[j];
if (newNumber == target)
{
r1.push_back(candidates[j]);
result.push_back(r1);
r1.clear();
break;
}
else if (newNumber < target)
{
r1.push_back(candidates[j]);
newNumber += candidates[j];
}
j--;
}
}
return result;
}
int main39()
{
vector<int> vec = {1};
vector<vector<int>> r = combinationSum(vec, 2);
return 0;
}