-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcombination_sum2.cpp
More file actions
83 lines (78 loc) · 2.3 KB
/
combination_sum2.cpp
File metadata and controls
83 lines (78 loc) · 2.3 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
76
77
78
79
80
81
82
/*
* =====================================================================================
*
* Filename: combination_sum2.cpp
*
* Description: 40. Combination Sum II. Given a collection of candidate numbers
* (candidates) and a target number (target), find all unique
* combinations in candidates where the candidate numbers sums to target.
* Each number in candidates may only be used once in the combination.
*
* Version: 1.0
* Created: 03/28/19 01:55:55
* Revision: none
* Compiler: gcc
*
* Author: Zhu Xianfeng (), xianfeng.zhu@gmail.com
* Organization:
*
* =====================================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <vector>
class Solution
{
public:
std::vector<std::vector<int>> combinationSum2(std::vector<int>& candidates, int target)
{
std::vector<std::vector<int>> combx;
std::vector<int> current;
std::sort(candidates.begin(), candidates.end());
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++)
{
if (i > start && candidates[i] == candidates[i - 1])
{
continue;
}
current->push_back(candidates[i]);
combine(candidates, i + 1, remain - candidates[i], current, combx);
current->pop_back();
}
}
};
int main(int argc, char* argv[])
{
std::vector<int> nums = {10, 1, 2, 7, 6, 1, 5};
int target = 8;
auto combx = Solution().combinationSum2(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;
}