读书人

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

发布时间: 2012-08-09 15:59:21 作者: rapoo

如何用递归的方式,求{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);} 

读书人网 >C++

热点推荐