编写递归函数的步骤,可以拆解为三个:
- 明确函数要做什么
- 找到递归的边界条件/终止条件,即找到递归出口
- 解决子问题,且找到函数的等价关系
力扣原题:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xnpvdm/
给定一个正整数 n ,输出外观数列的第 n 项。
「外观数列」是一个整数序列,从数字 1 开始,序列中的每一项都是对前一项的描述。
你可以将其视作是由递归公式定义的数字字符串序列:
- countAndSay(1) = “1”
- countAndSay(n) 是对 countAndSay(n-1) 的描述,然后转换成另一个数字字符串。
解题思路:
- 明确函数要做什么
class Solution(object):
#用来得到外观数列(字符串)
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
- 找到递归的边界条件/终止条件,即找到递归出口
class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
if n==1: #递归出口
return "1"
- 解决子问题,且找到函数的等价关系
class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
if n==1:
return "1"
s = self.countAndSay(n-1) #找到等价关系
ans = "" #解决子问题
start =0
end=0
while end <len(s):
while end < len(s) and s[start]==s[end]:
end +=1
ans = ans+str(end-start)
ans = ans + str(s[start])
start = end
return ans