File tree 1 file changed +42
-0
lines changed
1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ """
3
+ 38. 外观数列
4
+ https://leetcode-cn.com/problems/count-and-say/
5
+ 给定一个正整数 n ,输出外观数列的第 n 项。
6
+ 「外观数列」是一个整数序列,从数字 1 开始,序列中的每一项都是对前一项的描述。
7
+ 你可以将其视作是由递归公式定义的数字字符串序列:
8
+ countAndSay(1) = "1"
9
+ countAndSay(n) 是对 countAndSay(n-1) 的描述,然后转换成另一个数字字符串。
10
+ """
11
+ def countAndSay (self , n : int ) -> str :
12
+ dp = ['' for _ in range (n )]
13
+ i = 0
14
+ while i < n :
15
+ if i == 0 :
16
+ dp [i ] = '1'
17
+ i += 1
18
+ continue
19
+ res = ''
20
+ tmp = (dp [i - 1 ][0 ], 0 )
21
+ for j in range (len (dp [i - 1 ])):
22
+ if dp [i - 1 ][j ] == tmp [0 ]:
23
+ tmp = (tmp [0 ], tmp [1 ] + 1 )
24
+ else :
25
+ res = res + str (tmp [1 ]) + tmp [0 ]
26
+ tmp = (dp [i - 1 ][j ], 1 )
27
+
28
+ if j == len (dp [i - 1 ]) - 1 :
29
+ res = res + str (tmp [1 ]) + tmp [0 ]
30
+
31
+ dp [i ] = res
32
+ i += 1
33
+ return dp [- 1 ]
34
+
35
+
36
+ so = Solution ()
37
+ # 1211
38
+ print (so .countAndSay (4 ))
39
+ # 111221
40
+ print (so .countAndSay (5 ))
41
+ # 312211
42
+ print (so .countAndSay (25 ))
You can’t perform that action at this time.
0 commit comments