背包问题

输入两个整数 n 和 m,从数列1,2,3.......n 中 随意取几个数,使其和等于 m ,要求将其中所有的可能组合列出来。

 1 #include<list>
 2 #include<iostream>
 3 using namespace std;
 4 
 5 list<int> list1;
 6 
 7 void find_factor(int sum, int n)
 8 {
 9     // 递归出口
10     if (sum <= 0 || n <= 0)
11         return;
12 
13     // 输出找到的结果 
14     if (sum == n)
15     {
16         for (list<int>::iterator ite = list1.begin(); ite != list1.end(); ite++)
17             cout << *ite << " + ";
18         cout << n << endl;
19     }
20 
21     //典型的01背包问题
22     list1.push_back(n);         //放n,n-1个数填满sum-n 
23     find_factor(sum - n, n - 1);
24     list1.pop_back();         //不放n,n-1个数填满sum 
25     find_factor(sum, n - 1);
26 }
27 
28 int main()
29 {
30     int sum, n;
31     cout << "请输入你要等于多少的数值sum:" << endl;
32     cin >> sum;
33     cout << "请输入你要从1.....n数列中取值的n:" << endl;
34     cin >> n;
35     cout << "所有可能的序列,如下:" << endl;
36     find_factor(sum, n);
37 
38     system("pause");
39     return 0;
40 }

 

posted on 2016-07-19 15:04  已停更  阅读(237)  评论(0编辑  收藏  举报