这一路上,他一共遇到店5
次,遇到花10
次,已知最后一次遇到的是花,他正好把酒喝光了。
请你计算李白遇到店和花的次序,可以把遇店记为a
,遇花记为b
。则:babaabbabbabbbb
就是合理的次序。像这样的答案一共有多少呢?请你计算出所有可能方案的个数(包含题目给出的)。
PHP代码实现:
$count = 0;
$a = array();
function show($a, $num)
{
$i = 0;
while ($i < $num) echo $a[$i++];
echo '<br />';
}
function forward_recursion($i, $store, $flower, $wine)
{
if($store > 5 || $flower > 10){
return;
}
else if($store == 5 && $flower == 10 && $i == 15){
if ($GLOBALS['a'][14] == 'b' && $wine == 0){
$GLOBALS['count']++;
show($GLOBALS['a'], 15);
}
return;
}
$GLOBALS['a'][$i] = 'a';
forward_recursion($i + 1, $store + 1, $flower, $wine * 2); //逢店加一倍
$GLOBALS['a'][$i] = 'b';
forward_recursion($i + 1, $store, $flower + 1, $wine - 1); //遇花喝一斗
}
forward_recursion(0,0,0,2);
echo $count;
运行结果:
ababbbbbabababb
abbabbabbbababb
abbabbbaabbbabb
abbabbbabaabbbb
abbbaabbabbbabb
abbbaabbbaabbbb
abbbabaabbabbbb
baababbbbbababb
baabbabbabbbabb
baabbabbbaabbbb
baabbbaabbabbbb
babaababbbbbabb
babaabbabbabbbb
bababaababbbbbb
14