leetcode 1137. N-th Tribonacci Number python 解法

一.问题描述

The Tribonacci sequence Tn is defined as follows: 

T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0.

Given n, return the value of Tn.

 

Example 1:

Input: n = 4
Output: 4
Explanation:
T_3 = 0 + 1 + 1 = 2
T_4 = 1 + 1 + 2 = 4

Example 2:

class Solution:
    def tribonacci(self, n: int) -> int:
        temp={0:0,1:1,2:1}
        if n in temp:
            return temp[n] 
        rst=[0]*(n+1)
        rst[0],rst[1],rst[2]=0,1,1
        for i in range(3,n+1):
            rst[i]=rst[i-1]+rst[i-2]+rst[i-3]
        return rst[n]
Input: n = 25
Output: 1389537

 

Constraints:

  • 0 <= n <= 37
  • The answer is guaranteed to fit within a 32-bit integer, ie. answer <= 2^31 - 1.

二.解决思路

按照公式算,把每一步的结果保存下来以便下一次计算。

注意一下n为0,1,2的情况。

这道题如果n特别大,在C++里面比较难,要学习大整数的表示,可以思考一下练练手。

更多leetcode算法题解法请关注我的专栏leetcode算法从零到结束或关注我

欢迎大家一起套路一起刷题一起ac

三.源码

class Solution:
    def tribonacci(self, n: int) -> int:
        temp={0:0,1:1,2:1}
        if n in temp:
            return temp[n] 
        rst=[0]*(n+1)
        rst[0],rst[1],rst[2]=0,1,1
        for i in range(3,n+1):
            rst[i]=rst[i-1]+rst[i-2]+rst[i-3]
        return rst[n]

 

你可能感兴趣的:(leetcode算法从零到结束,python,leetcode,算法,编程)