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