首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

怎么用递归的方式,求{a,b,c}的所有子集

2012-08-09 
如何用递归的方式,求{a,b,c}的所有子集?如题[解决办法]C/C++ code#includeiostream#includecstring#in

如何用递归的方式,求{a,b,c}的所有子集?
如题

[解决办法]

C/C++ code
#include<iostream>#include<cstring>#include<cstdio>using namespace std;#define MAX_LENGTH 4void build(char str[], int n);int main(){    char string[MAX_LENGTH] = "abc"; //实例集合放在数组中    build(string, MAX_LENGTH - 1);    return 0;}void build(char str[], int n){    if(n == 0) //控制输出    {        for(int i = 0; i <MAX_LENGTH; i++)            if(str[i]!=' ')            {                putchar(str[i]);                putchar(' ');            }        putchar('\n');    }    else    {        build(str, n - 1);        char newstr[MAX_LENGTH] = {0}; //去掉就把该位置的元素置成空        strcat(newstr, str);        newstr[n-1] = ' ';        build(newstr, n - 1);    }}
[解决办法]
C/C++ code
#include <iostream>using namespace std;int count = 0;char elem[] = { 'a', 'b', 'c' };int index[] = { 0, 0, 0 };void output(){    cout << "sub" << ++count << " : ";    for (int i = 0; i < 3; ++i) {        if (index[i]) {            cout << elem[i];        }    }    cout << endl;}void doit(int i){    if (i < 3) {       index[i] = 0;       doit(i+1);       index[i] = 1;       doit(i+1);    }    else {        output();    }}void doit(){    doit(0);}int main(){    doit();    return(0);} 

热点排行