forked from haoel/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
combinationSum.cpp
97 lines (84 loc) · 2.5 KB
/
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
97
// Source : https://oj.leetcode.com/problems/combination-sum/
// Author : Hao Chen
// Date : 2014-07-19
/**********************************************************************************
*
* Given a set of candidate numbers (C) and a target number (T), find all unique combinations
* in C where the candidate numbers sums to T.
*
* The same repeated number may be chosen from C unlimited number of times.
*
* Note:
*
* All numbers (including target) will be positive integers.
* Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
* The solution set must not contain duplicate combinations.
*
* For example, given candidate set 2,3,6,7 and target 7,
* A solution set is:
* [7]
* [2, 2, 3]
*
*
**********************************************************************************/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void combinationSumHelper(vector<int> &candidates, int start, int target, vector<int> &solution, vector< vector<int> > &result) {
if (target<0){
return;
}
if (target==0){
result.push_back(solution);
}
for(int i=start; i<candidates.size(); i++){
//remote duplicates
if (i>start && candidates[i] == candidates[i-1]) {
continue;
}
solution.push_back(candidates[i]);
combinationSumHelper(candidates, i, target - candidates[i], solution, result);
solution.pop_back();
}
}
vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
vector< vector<int> > result;
if (candidates.size()<=0){
return result;
}
sort(candidates.begin(), candidates.end());
vector<int> solution;
combinationSumHelper(candidates, 0, target, solution, result);
return result;
}
void printMatrix(vector< vector<int> > &vv)
{
for(int i=0; i<vv.size(); i++) {
cout << "[";
for(int j=0; j<vv[i].size(); j++) {
cout << " " << vv[i][j];
}
cout << "]" << endl;;
}
}
void printArray(vector<int> &v)
{
cout << "{";
for(int i=0; i<v.size(); i++) {
cout << " " << v[i];
}
cout << "}" << endl;
}
int main(int argc, char** argv)
{
int a[] = {4,2,3,3,5,7};
vector<int> v(a, a+sizeof(a)/sizeof(int));
int target = 7;
cout << "array = ";
printArray(v);
cout << "target = " << target << endl;
vector< vector<int> > vv = combinationSum(v, target);
printMatrix(vv);
return 0;
}