标题:李白打酒
话说大诗人李白,一生好饮。幸好他从不开车。
一天,他提着酒壶,从家里出来,酒壶中有酒2斗。他边走边唱:
无事街上走,提壶去打酒。
逢店加一倍,遇花喝一斗。
这一路上,他一共遇到店5次,遇到花10次,已知最后一次遇到的是花,他正好把酒喝光了。
请你计算李白遇到店和花的次序,可以把遇店记为a,遇花记为b。则:babaabbabbabbbb 就是合理的次序。像这样的答案一共有多少呢?请你计算出所有可能方案的个数(包含题目给出的)。
注意:通过浏览器提交答案。答案是个整数。不要书写任何多余的内容。
分析:
主要是运用递归搜索,找到所有的情况,遇店酒量加倍,遇花喝去一斗,两个递归对应两种情况,遍历得到所有的情况
c++代码:
01.
#include<stdio.h>
02.
#include<string>
03.
#include<iostream>
04.
using
namespace
std;
05.
int
t;
06.
void
digui(
int
j,
int
d,
int
h,string str)
07.
{
08.
09.
if
(d+h==15)
10.
{
11.
if
(j==0)
12.
{
13.
int
c=0;
14.
for
(
int
i=0; i<str.length(); i++)
15.
if
(str[i]==
'b'
)
16.
c++;
17.
if
(c==10&&str[14]==
'b'
)
18.
{
19.
t++;
20.
cout<<str<<endl;
21.
}
22.
}
23.
return
;
24.
}
25.
digui(j*2,d+1,h,str+
"a"
);
26.
digui(j-1,d,h+1,str+
"b"
);
27.
}
28.
int
main()
29.
{
30.
digui(4,1,0,
"a"
);
31.
digui(1,0,1,
"b"
);
32.
printf
(
"%d\n"
,t);
33.
return
0;
34.
}
- public class MrLBDaJiu {
- public static void main(String[] args) {
- digui(4, 1, 0, "a");// 遇到店
- digui(1, 0, 1, "b");// 遇到花
- System.out.println(result);
- }
- static int result;
- private static void digui(int j, int d, int h, String str) {
- if (d + h == 15) {
- if (j == 0) {
- int count = 0;
- for (int i = 0; i < str.length(); i++)
- if (str.charAt(i) == 'b')
- count++;
- if (count == 10 && str.charAt(14) == 'b') {
- result++;
- // System.out.println(str);
- }
- }
- return;
- }
- digui(j * 2, d + 1, h, str + "a");
- digui(j - 1, d, h + 1, str + "b");
- }
- }