-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcombinationsum.cpp
More file actions
51 lines (51 loc) · 1.29 KB
/
combinationsum.cpp
File metadata and controls
51 lines (51 loc) · 1.29 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
class Solution {
public:
vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
vector<vector<int>>ret;
if (candidates.empty())
{
return ret;
}
int end = 0;
int start = 0;
sort(candidates.begin(), candidates.end());
for (; end < candidates.size(); end++)
{
if (candidates[end]>target)
{
break;
}
}
end--;
vector<int>tmp;
getComSum(candidates, target, start, end, tmp, ret);
return ret;
}
private:
void getComSum(vector<int> &candidates, int target, int start, int end, vector<int>&tmp, vector<vector<int>>&ret)
{
if (candidates.empty() || start>end || start < 0 || end >= candidates.size())
{
return;
}
if (target == 0)
{
if (tmp.empty() != true)
{
ret.push_back(tmp);
}
return;
}
else if (target < 0)
{
return;
}
for (int i = start; i <= end; i++)
{
tmp.push_back(candidates[i]);
getComSum(candidates, target - candidates[i], i, end, tmp, ret);
tmp.pop_back();
}
return;
}
};