-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathFindSum.cpp
More file actions
49 lines (35 loc) · 833 Bytes
/
Copy pathFindSum.cpp
File metadata and controls
49 lines (35 loc) · 833 Bytes
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
#include <stdlib.h>
#include <vector>
#include <iostream>
using namespace std;
/*
输入两个数m和n ,从数列1,2,3,4,.....n这些数中挑选几个
使得和为m,找出所有的这样的组合
*/
void FindSum(int m,int n,vector<int>& vec)
{
if(m < 0 || n < 0)
return ;
if(m == 0)
{
vector<int>::iterator itr = vec.begin();
for(;itr != vec.end();itr++)
{
cout<<*itr<<" ";
}
cout<<endl;
return ;
}
vec.push_back(n); // 典型的背包问题
FindSum(m-n,n-1,vec); //放入一个元素 在剩下的元素满足剩下的要求
vec.pop_back();//不放入当期的元素 在剩下的元素满足所有的要求
FindSum(m,n-1,vec);
}
int main()
{
int sum = 9;
int n = 10;
vector<int> vec;
FindSum(sum, n, vec);
return 0;
}