-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcombination_sum.cpp
More file actions
76 lines (71 loc) · 2.02 KB
/
combination_sum.cpp
File metadata and controls
76 lines (71 loc) · 2.02 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/*
* =====================================================================================
*
* Filename: combination_sum.cpp
*
* Description: 39. Combination Sum. Given a set of candidate numbers (candidates)
* (without duplicates) and a target number (target), find all unique
* combinations in candidates where the candidate numbers sums to target.
*
* Version: 1.0
* Created: 03/26/19 02:01:38
* Revision: none
* Compiler: gcc
*
* Author: Zhu Xianfeng (), xianfeng.zhu@gmail.com
* Organization:
*
* =====================================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <vector>
class Solution
{
public:
std::vector<std::vector<int>> combinationSum(const std::vector<int>& candidates, int target)
{
std::vector<std::vector<int>> combx;
std::vector<int> current;
combine(candidates, 0, target, ¤t, &combx);
return combx;
}
private:
void combine(const std::vector<int>& candidates, int start, int remain, std::vector<int>* current, std::vector<std::vector<int>>* combx)
{
if (remain == 0)
{
if (current->size() > 0)
{
combx->push_back(*current);
}
return;
}
else if (remain < 0)
{
return;
}
for (int i = start; i < candidates.size(); i++)
{
current->push_back(candidates[i]);
combine(candidates, i, remain - candidates[i], current, combx);
current->pop_back();
}
}
};
int main(int argc, char* argv[])
{
std::vector<int> nums = {2, 3, 5};
int target = 8;
auto combx = Solution().combinationSum(nums, target);
printf("Number of combinations: %lu\n", combx.size());
for (const auto& item: combx)
{
for (auto n: item)
{
printf("%d ", n);
}
printf("\n");
}
return 0;
}