博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
输入两个整数n和m, 从数列1,2,...,n中任意选择几个数,使其和等于m, 要求编写程序输出所有的组合
阅读量:4135 次
发布时间:2019-05-25

本文共 578 字,大约阅读时间需要 1 分钟。

#include "stdafx.h"#include 
using namespace std;int length;void PrintSolutions(int *flag) { for (int i=0; i
> m >> n; cout << "The solution is:" << endl; length = n; int *flag = (int *)malloc(sizeof(int)*n); memset(flag, 0, sizeof(flag)); BagProblem(m,n,flag); //delete flag;//这个地方犯了一个原则性的错误 new和delete成对使用, malloc应该和free成对使用,要不然就会造成内存泄露 free(flag); return 0; }
上面的代码看懂不是很难吧,递归的程序就是可读性好,我觉得这个代码的亮点应该就是flag数组的使用,充分利用了递归的性质,只是很简单的一个数组就完成了所有组合的输出。在每次把flag[i]设置为1之后就进入递归,代表了将i放入背包,当退出递归函数的时候,肯定要将flag[i]赋为0,因为这时候i已经不在背包中了。

转载地址:http://hbsvi.baihongyu.com/

你可能感兴趣的文章
1136 . 欧拉函数
查看>>
面试题:强制类型转换
查看>>
Decorator模式
查看>>
Template模式
查看>>
State模式
查看>>
Observer模式
查看>>
Iterator模式
查看>>
电灯泡 (容斥原理)
查看>>
B - Number Puzzle ZOJ - 2836(容斥原理 数学)
查看>>
E - Olympic Medal CodeForces - 215B(数学 思维)
查看>>
codeforces1073D. Berland Fair
查看>>
codeforces 1073B. Vasya and Books
查看>>
Queue at the School CodeForces - 266B
查看>>
A - Average distance HDU - 2376(树形)
查看>>
B - Adding Digits CodeForces - 260A
查看>>
Party at Hali-Bula POJ - 3342(树形dp)
查看>>
E - Balls and Boxes CodeForces - 260C(思维)
查看>>
A - Anniversary party HDU - 1520(没有上司的舞会)
查看>>
B - Greg's Workout CodeForces - 255A(思维)
查看>>
E - Code Parsing CodeForces - 255B(思维)
查看>>