編寫一個函式,用來輸出n 個元素的所有子集
阿新 • • 發佈:2019-02-03
#include<iostream> using namespace std; int str[]={1,2,3,4,5,6,7}; bool bo[7]; long xnum=0; /* int print(int i) { if(i>=7) i>=7 就輸出結果中的一個 { int j,k=0; ++xnum; cout<<"No."<<xnum<<'='; cout<<"{"; for(j=0; j<7; j++) if(bo[j]) { if(k) cout<<','; cout<<str[j]; ++k; } cout<<"}"<<endl; return 0; } else i<7就繼續下一個數 { bo[i]=true; 第i個元素放入集合中並繼續 print(i+1); bo[i]=false; 第i個元素不放入集合中 print(i+1); } return 0; } int main( int argc, char * argv[] ) { print(0); return 0; } #include <stdio.h> #include <string.h> #define MAX_LENGTH 100 /*集合的最大元素個數*/ void PowerSet(char*, int, char*,int *); int main() { char a[MAX_LENGTH]; /*儲存輸入的集合*/ char set[MAX_LENGTH]={"\0"}; /*儲存集合的冪集元素*/ int NumOfPowerSet=0; /*冪集元素記數*/ printf("Input the elements:"); scanf("%s",a); printf("----------------------------\n"); PowerSet(a,0,set,&NumOfPowerSet); /*呼叫遞迴函式*/ printf("----------------------------\n"); printf("Number of PowerSet: %d\n",NumOfPowerSet); return 1; } /* 引數說明: char* a : 待求冪集的集合 int i : 當前分析到集合的第i個元素 char* set : 儲存當前冪集元素狀態 int* Num : 冪集元素記數 */ void PowerSet(char* a, int i, char* set, int * Num) { char TempSet[MAX_LENGTH]; strcpy(TempSet,set); if(i>=strlen(a)) { printf("{%s}\n",set); (*Num)++; } else { PowerSet(a,i+1,TempSet,Num); /* 當前 *a 放到 set裡 */ strncat(TempSet,(a+i),1); PowerSet(a,i+1,TempSet,Num); /* 跳過 *a */ } } /* 輸入測試資料:ABCD,表示集合{A,B,C,D},得到輸出資料如下:Input the elements:ABCD ------------------------- {}{D}{C}{CD}{B}{BD}{BC}{BCD}{A}{AD}{AC}{ACD}{AB}{ABD}{ABC}{ABCD} -------------------------Number of PowerSet: 16 */