背包问题
来源:互联网 发布:越南古代服饰淘宝 编辑:程序博客网 时间:2024/06/06 14:13
2010 年中兴面试题
编程求解:
输入两个整数n 和m,从数列1,2,3.......n 中随意取几个数,
使其和等于m ,要求将其中所有的可能组合列出来.
这道题的思路参考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 }
0 0
- 【无限背包】背包问题
- 背包问题---01背包
- 背包问题--部分背包
- 背包问题
- 背包问题
- 背包问题
- 背包问题
- 背包问题
- 背包问题
- 背包问题
- 背包问题
- 背包问题
- 背包问题
- 背包问题
- 背包问题
- 背包问题
- 背包问题
- 背包问题
- php的输出缓存及其相关函数
- Java泛型擦除
- Fle.createNewFile() 和 Fle.createTempFile() 比较和区别
- 1619: [Usaco2008 Nov]Guarding the Farm 保卫牧场
- win7 自定义安装php iis
- 背包问题
- 和为s的两个数字VS和为s的连续整数序列(面试题 41)
- 学习总结十八:Hbase数据库介绍
- PowerManager之UserActivity
- Java递归搜索指定文件夹下的匹配文件
- 温度PID控制
- 新生报到
- LeetCode——String to Integer (atoi)
- double long float类型读入读出 double取模 fmod