zoukankan      html  css  js  c++  java
  • 背包问题

    输入两个整数 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 }
  • 相关阅读:
    Centos7:mariadb替换mysql
    CentOS5 部署 戴尔OMSA
    《Zero MQ》
    可扩展的Web架构和分布式系统
    队列实现
    超级好用的正则表达式网站
    <转>undefined与null的区别
    JS事件
    sublime text 3 快捷键
    设置className的方式(不使用setAttribute)
  • 原文地址:https://www.cnblogs.com/raichen/p/5684028.html
Copyright © 2011-2022 走看看