abc排列问题
例:
用戶輸入:a,b,c
輸出: a,b,c,ab,ac,bc,abc
解:此程序應(yīng)不僅適用于3個(gè)字符的情況~運(yùn)用遞歸即可解決:
法1:
[cpp]?view plaincopyprint? #include<stdio.h>?? #include<string.h>?? ?? #define?MAX?100?? ?? int?top?=?0;????????//緩沖區(qū)指針。?? int?count?=?1;??????//統(tǒng)計(jì)組合數(shù)。?? ?? void?search(char?*a,?char?*b,?int?start)????//a:待組合的字符串;b:緩沖區(qū)數(shù)組;start:當(dāng)前開始位置。?? {?? ????int?i,?len?=?strlen(a);?? ????for(i?=?start;?i?<?len;?i++)?? ????{?? ????????b[top++]?=?a[i];????????//將選出的字符存入緩沖區(qū)。?? ????????printf("Line:?%2d???%s\n",?count++,?b);?????//將緩沖區(qū)中選出的字符輸出。?? ????????if(i?<?len-1)?search(a,?b,?i+1);?????????//若能繼續(xù)選擇字符,則遞歸。?? ????????b[--top]?=?'\0';????????//將緩沖區(qū)中最后一個(gè)字符彈出,緩沖區(qū)指針前移一個(gè)單位。?? ????}?? }?? ?? int?main()?? {?? ????char?a[MAX],?b[MAX];?? ????int?n;?? ????memset(a,?'\0',?sizeof(a));?? ????memset(b,?'\0',?sizeof(b));?? ????printf("請(qǐng)輸入待組合字符串:");?? ????scanf("%s",?a);?? ????search(a,?b,?0);?? ????return?0;?? }?? 運(yùn)行結(jié)果:
法2: [cpp]?view plaincopyprint? #include?<stdio.h>?? #include?<string.h>?? ?? int?main()?? {?? ????int?i,?j,?n;?? ????char?str[100];?? ????scanf("%s",?str);?? ????n?=?strlen(str);?? ????for?(i?=?1;?i?<?1<<n;?++i)//組合的個(gè)數(shù)。?? ????{?? ????????for?(j?=?0;?j?<=?n-1;?++j)//依次輸出符合條件的字符。?? ????????????if?(1<<j?&?i)?putchar(str[j]);?? ????????puts("");?? ????}?? ????return?0;?? }?? 結(jié)果:
法2: [cpp]?view plaincopyprint?
總結(jié)
- 上一篇: 实现BFS之“营救”
- 下一篇: 蚂蚁--模拟