-
Notifications
You must be signed in to change notification settings - Fork 160
/
Copy pathPrint all combinations.cpp
76 lines (44 loc) · 1.16 KB
/
Print all combinations.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
/*
Given a positive number N, print all possible combinations of non-negative integer sum to N.
For example:
suppose N=5, print:
1+1+1+1+1
1+1+1+2
...
*/
/*
solution: Usually, we solve combination problem using backtrakcing.
For each number sum, we iterate all integers from 1 to sum. Print
the result when sum == 0. In order to remove duplicates such as 1 + 2 and
2 + 1, we only iterate from factor larger than previous one.
*/
#include<iostream>
#include<vector>
using namespace std;
void Printcombination(vector<int> vec) {
vector<int>::iterator it = vec.begin();
for (; it != vec.end(); ++it) {
cout<<*it<<" ";
}
cout<<endl;
}
void Search(vector<int>& comb, int num, int target) {
if ( num ==0 ) {
Printcombination(comb);
return;
}
if ( num < 0 ) return;
int i = num == target? 1 : comb.back(); //always iterate from the factor larger than previous one
for (; i <= num; ++i) {
comb.push_back(i);
Search(comb, num - i, target);
comb.pop_back();
}
}
int main() {
vector<int> vec;
int num = 6;
int target = num;
Search(vec, num, target);
return 0;
}