本题目本质和爬楼梯是一样的,主要运用的是递归来解题。
python
class Solution:
my_dict = {}
def tribonacci(self, n: int) -> int:
if self.my_dict.get(n) is not None: # 先判断有没有计算过这个值
return self.my_dict.get(n)
tempResult = 0
if n >= 3:
tempResult = self.tribonacci(n - 1) + self.tribonacci(n - 2) + self.tribonacci(n - 3)
elif n == 2:
tempResult = 1
elif n == 1:
tempResult = 1
else:
tempResult = 0
self.my_dict[n] = tempResult
return tempResult