-
Notifications
You must be signed in to change notification settings - Fork 3
/
sumOfNum.cpp
60 lines (55 loc) · 1.13 KB
/
sumOfNum.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
#include <iostream>
#include <vector>
using namespace std;
void sumOfNum1(vector<vector<int> > &result, vector<int> &path, int sum, int start, int n)
{
if(sum < 0 || start > n)
{
return;
}
if(sum == 0)
{
result.push_back(path);
return;
}
for(int i = start; i<= n; i++)
{
path.push_back(i);
sumOfNum1(result, path, sum - i, i+1, n);
path.pop_back();
}
}
void sumOfNum(vector<vector<int> > &result, vector<int> &path, int sum, int n)
{
if(sum < 0 || n <= 0)
{
return;
}
if(sum == 0)
{
result.push_back(path);
return;
}
path.push_back(n);
// cout<<"pushing "<<n<<" looking for "<<sum-n<<endl;
sumOfNum(result, path, sum - n, n-1);
// cout<<"Poping out "<<path.back()<<endl;
path.pop_back();
sumOfNum(result, path, sum, n-1);
}
int main()
{
cout<<"Test"<<endl;
vector<vector<int> > result;
vector<int> path;
sumOfNum1(result, path, 7, 1, 6);
//sumOfNum(result, path, 7, 6);
for(int i = 0; i < result.size(); i++)
{
for(int j = 0; j < result[i].size(); j++)
{
std::cout <<result[i][j]<< " ";
}
std::cout << endl;
}
}