已经做出来了,但我不知道为什么这是对的。我是凑数字凑的。
gques str = count str 1
where
len = length str
count [] _ = 1
count ('A':cs) n =
sum $ map (count cs) [1..n]
count ('B':cs) n =
sum $ map (count cs) [1..len-n+1]
第一步和最后一步都可以加速一下,但那样缺乏美感。动态规划,有空再说。
--
Ray Stinger, nickname Lich_Ray
God is in his heaven, all's right with the world.
-------------------------------------------------
let focus = 'computing' in where:
http://lichray.javaeye.com
let focus = 'computing' in here:
http://let-in.blogspot.com
在 08-7-3,liuxinyu<liuxi...@gmail.com> 写道:
现在这个程序就能算任意长度的串了:
use strict;
use warnings;
use Memoize;
use List::Util qw(reduce sum);
sub gques {
my $str = shift;
our $len = length $str;
sub count {
my ($s, $n) = @_;
if ($s eq "") {
return 1;
}
my $c = substr $s, 0, 1;
if ($c eq 'A') {
sum(map { count ((substr $s, 1), $_) } (1..$n));
} elsif ($c eq 'B') {
sum(map { count ((substr $s, 1), $_) } (1..$len-$n+1));
}
}
memoize 'count';
count $str, 1;
}
我写这个程序80%都花在了查一个Bug上,这个Bug是重叠函数调用....少了两个括号。Bug的弱智程度真的和找出它需要的时间成正比....
DB<1> print 'Result: '.(gques "ABBABAABABABBABAABABBBAABA").';
Result: 3.1986296886995e+028
接下来更让我晕倒就是这个了...Perl居然不像Python一样直接支持大整数....
get ab = sum $ foldl f [1] ab
where f last 'A' = scanl (+) 0 last
f last 'B' = scanr (+) 0 last
--
Alecs King
这仍然是直接生成的方法。不过我也很郁闷,因为我用聪明一点的方法做错了...
我觉得我特好玩儿,因为受到了楼上如此简短的代码的刺激,1分钟就把我自己的算法改对了 :)
gques str = count str 1
where
len = length str + 1
count [] _ = 1
count ('A':cs) n =
sum $ map (count cs) [n+1..len-length cs]
count ('B':cs) n =
sum $ map (count cs) [1..n]
那个 Perl 的加记忆的版本就不发了,没意思。我们期待手动计算的人。