之前用遞歸求出了多少種情況,如果要打印出所有的結果,就需要一個數組來存放可能的情況:
/******************************************************
題目:“李白街上走,提壺去買酒,遇店加一倍,見花喝一斗”,
途中,遇見5次店,見了10此花,壺中原有2斗酒,最后剛好喝
完酒,要求最后遇見的是花,求可能的情況有多少種?原理:起點位置店和花都為0,酒為2。遇到一次店,酒*2。遇
到一次花,酒-1,當5次店和9次花都遇完,酒為1。遞歸終止條
件為,店和花超過題中所給或滿足題目要求。
*******************************************************/#include <stdio.h>int count = 0;//pre為 1 時代表碰到店,為 0 時代表碰到花,確保最后一次是花
void fun(int store, int flower, int alco, int pre, char* ch, int index)
{//遞歸 終止條件if (0 == store && 0 == flower){if (0 == alco && 0 == pre){int i = 0;for (i = 0; i < 15; i++) //輸出可能的組合{printf ("%c", ch[i]);}putchar ('\n');count++;}return ;}//終止條件結束if (0 < store){ch[index] = 'a'; //a代表碰到的是店 fun(store - 1, flower, alco * 2, 1, ch, index + 1);}if (0 < flower){ch[index] = 'b'; //b代表碰到的是花fun(store, flower - 1, alco - 1, 0, ch, index + 1);}
}int main()
{ char ch[20]; //定義一個數組用以存放可能的情況fun(5, 10, 2, -1, ch, 0); //pre賦初值-1printf ("共有 %d 種可能\n", count);return 0;
}