鋸齒序列是序列,其中每一個元素是比它的鄰居更少或更多:1 3 2
和2 1 2
是曲折,1 2 3
和1 2 2
不是。計數Z字形序列
隨着給定的n兩個數,K找出如何大小爲n的許多序列可以從數字1..k
實施例來生成:N = 3,K = 3的答案:10
121,212 ,131,313,232,323,132,231,312,213(爲了清楚起見,不需要生成)
我來到這個解決方案。請告訴我是否可以做得更好。
import sys
ZAG = {}
ZIG = {}
def zag(n, i):
result = 0
for j in xrange(1, i):
if (n - 1, j) not in ZIG:
ZIG[(n - 1, j)] = zig(n - 1, j)
result += ZIG[(n - 1, j)]
return result
def zig(n, i):
result = 0
for j in xrange(i + 1, MAX_NUMBER + 1):
if (n - 1, j) not in ZAG:
ZAG[(n - 1, j)] = zag(n - 1, j)
result += ZAG[(n - 1, j)]
return result
def count(n):
if n == 1:
return MAX_NUMBER
result = 0
for i in xrange(1, MAX_NUMBER + 1):
ZIG[(1, i)] = 1
ZAG[(1, i)] = 1
for i in xrange(1, MAX_NUMBER + 1):
result += 2*zag(n, i)
return result
def main(argv):
global MAX_NUMBER
MAX_NUMBER = int(argv[1])
print count(int(argv[0]))
if __name__ == "__main__":
main(sys.argv[1:])
可能重複:http://stackoverflow.com/questions/6914969/dynamic-programming-find-longest-subsequence-that-is-zig-zag –