首页 > 其他 > 详细

背包问题

时间:2016-07-19 15:26:34      阅读:163      评论:0      收藏:0      [点我收藏+]

输入两个整数 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 }

 

背包问题

原文:http://www.cnblogs.com/raichen/p/5684028.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!