【leetcode】1137. N-th Tribonacci Number

题目如下:

The Tribonacci sequence Tn is defined as follows: 

T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2for 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:

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.

解题思路:动态规划入门级的题目。

代码如下:

class Solution(object):
    fib_list = []
    def tribonacci(self, n):
        """
        :type n: int
        :rtype: int
        """
        f = [0,1,1]
        if len(self.fib_list) == 0:
            for i in range(0,38):
                if i <= 2:
                    self.fib_list.append(f[i])
                    continue
                self.fib_list.append(self.fib_list[-1] + self.fib_list[-2] + self.fib_list[-3])

        return self.fib_list[n]

 

转载于:https://www.cnblogs.com/seyjs/p/11302149.html

你可能感兴趣的:(数据结构与算法)