现在的位置: 首页 > 综合 > 正文

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

2013年08月20日 ⁄ 综合 ⁄ 共 890字 ⁄ 字号 评论关闭

这道题的思路参考0-1背包:定义函数F(n,m)来求解这个问题,那么F(n,m)可以分解为两个子问题F(n-1,m)和F(n-1,m-n).由于题目要求列出所有的组合,使用类似动态规划的方法比较复杂,我在这里直接使用递归来解决这个问题。虽然效率可能不是很好,但是代码的可读性还是比较好的

复制代码
 1 #include "stdafx.h"
 2 #include <iostream>
 3 
 4  using namespace std;
 5 int length;
 6 void PrintSolutions(int *flag)
 7 {
 8     for (int i=0; i<length; i++)
 9     {
10         if (flag[i] == 1)
11         {
12             cout << i+1 << "  ";
13         }
14     }
15     cout << endl;
16 }
17 
18 void BagProblem(int m, int n, int *flag)
19 {
20     if(n<1 || m<1)
21         return;
22     if(m < n)
23         n = m;
24     if (n == m)
25     {
26         flag[n-1] = 1;
27         PrintSolutions(flag);
28         flag[n-1] = 0;
29     }
30     flag[n-1] = 1;
31     BagProblem(m-n, n-1, flag);
32     flag[n-1] = 0;
33 
34     BagProblem(m, n-1, flag);
35 }
36 
37 int main(int argc, char* argv[])
38 {
39     int m, n;
40     cout << "Please input the m and n:" << endl;
41     cin >> m >> n;
42     cout << "The solution is:" << endl;
43     length = n;
44     int *flag = (int *)malloc(sizeof(int)*n);
45     memset(flag, 0, sizeof(flag));
46     BagProblem(m,n,flag);
47     //delete flag;//这个地方犯了一个原则性的错误 new和delete成对使用, malloc应该和free成对使用,要不然就会造成内存泄露
48     free(flag);
49     return 0;
50 }

抱歉!评论已关闭.