The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, …
1 is read off as “one 1” or 11.
11 is read off as “two 1s” or 21.
21 is read off as “one 2, then one 1” or 1211.
Given an integer n, generate the nth sequence.
class Solution(object):
def countAndSay(self,n):
if n == 1:
return “1”
else:
b = self.countAndSay(n-1)
return self.count(b)
def count(self,b):
a = “”
c = 0
i = 0
while (i < len(b)):
eql = b[i]
while b[i] == eql:
c += 1
i += 1
if i == len(b):
break
a += (str(c) + b[i - 1])
c = 0
return a
本文介绍了一种生成计数并说序列的方法。通过递归的方式生成第n个序列,首先定义基本序列“1”,然后通过读取前一个序列中的数字及连续出现次数来生成下一个序列。例如,“1”被读作“one 1”即“11”,“11”被读作“two 1s”即“21”。以此类推,生成任意长度的计数并说序列。
1104

被折叠的 条评论
为什么被折叠?



