First they ignore you
then they ridicule you
then they fight you
then you win
    -- Mahatma Gandhi
Chinese => English     英文 => 中文             
随笔-221  评论-1047  文章-0  trackbacks-0
写一个算法生成n位编码的编码串(结果有多种,任意一种都可以接受)并且符合如下条件:相邻的两个编码之间有且只能有一位不同,并给出时间与空间复杂度

比如 2位的二进制的编码生成的编码串:00 01 11 10
比如 3位的二进制编码生成的编码串:001 011 111 101 100 110 010 000

Groovy实现:
List generateBinaryStrings(int length) {
    
if (1 == length) return ['0''1']
    List tempBinaryStrings 
= generateBinaryStrings(length - 1)
    
return [tempBinaryStrings.collect{ "0$it" }, tempBinaryStrings.reverse().collect{ "1$it" }].flatten()
}

println generateBinaryStrings(
2)
println generateBinaryStrings(
3)

运行结果:
[00, 01, 11, 10]
[000, 001, 011, 010, 110, 111, 101, 100]


题目来源:http://www.blogjava.net/copydogcn/archive/2008/04/19/194256.html

附:朝花夕拾——Groovy & Grails
posted on 2008-04-20 21:13 山风小子 阅读(3460) 评论(11)  编辑  收藏 所属分类: Groovy & GrailsAlgorithm