中兴面试题 01背包问题

来源:互联网 发布:sep软件 编辑:程序博客网 时间:2024/05/16 19:02

背包问题就是包要满,但是01背包允许包不满

 

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

二,解释:比如输入m=4  n=4 则输出为:4

                                                                   1+3   而2+2不正确,因为重复输出数字了

                  中心思想:1)如果1+2+3+……+n<m 则不存在这个数

                                    2)如果m<n 则应该让n=m //因为m--->n之间的数都已经大于m了 没必要再计算了

                                    3)如果m=n 输出n

                                    4)如果m>n   递归循环

                  源码采用原型:0-1背包问题

                                 参考博客:http://blog.csdn.net/tianshuai11/article/details/7025464

三,源码:(类似源码五)

#include<list>

[html] view plaincopyprint?
  1. #include<iostream>    
  2. using namespace std;    
  3.     
  4. list<int> list1;    
  5. void find_factor(int sum, int n)     
  6. {    
  7.     // 递归出口    
  8.     if(n <= 0 || sum <= 0)    
  9.         return;    
  10.         
  11.     // 输出找到的结果    
  12.     if(sum == n)    
  13.     {    
  14.         // 反转list    
  15.         list1.reverse();    
  16.         for(list<int>::iterator iter = list1.begin(); iter != list1.end(); iter++)    
  17.             cout << *iter << " + ";    
  18.         cout << n << endl;    
  19.         list1.reverse();        
  20.     }    
  21.         
  22.     list1.push_front(n);      //典型的01背包问题    
  23.     find_factor(sum-n, n-1);   //放n,n-1个数填满sum-n    
  24.     list1.pop_front();    
  25.     find_factor(sum, n-1);     //不放n,n-1个数填满sum     
  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.     return 0;    
  38. }    


原创粉丝点击