Leetcode-1137. N-th Tribonacci Number 第 N 个泰波那契数 (DP)

题目

泰波那契序列 Tn 定义如下:
T 0 = 0 T_0 = 0 T0=0, T 1 = 1 T_1 = 1 T1=1, T 2 = 1 T_2 = 1 T2=1, 且在 n >= 0 的条件下 T n + 3 = T n + T n + 1 + T n + 2 T_{n+3} = T_{n} + T_{n+1} + T_{n+2} Tn+3=Tn+Tn+1+Tn+2
给你整数 n,请返回第 n 个泰波那契数 Tn 的值。
链接:https://leetcode.com/problems/n-th-tribonacci-number/

The Tribonacci sequence T n T_n Tn is defined as follows:

T 0 = 0 T_0 = 0 T0=0, T 1 = 1 T_1 = 1 T1=1, T 2 = 1 T_2 = 1 T2=1, and T n + 3 = T n + T n + 1 + T n + 2 T_{n+3} = T_{n} + T_{n+1} + T_{n+2} Tn+3=Tn+Tn+1+Tn+2 for n > = 0 n >= 0 n>=0.

Given n, return the value of T n T_n Tn.

Example:

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

思路及代码

DP
  • 同斐波那契Fibonacci
class Solution:
    def tribonacci(self, n: int) -> int:
        if n == 0:
            return 0
        if n == 1:
            return 1
        if n == 2:
            return 1
        t0 = 0
        t1 = 1
        t2 = 1
        for i in range(3, n+1):
            t = t0 + t1 + t2
            t0 = t1
            t1 = t2
            t2 = t
        return t

复杂度

T = O ( n ) O(n) O(n)
S = O ( 1 ) O(1) O(1)

你可能感兴趣的:(Leetcode,leetcode,动态规划,算法,python)