1137. 第 N 个泰波那契数
JalanJiang opened this issue · 3 comments
JalanJiang commented
JalanJiang commented
动态规划
class Solution:
def tribonacci(self, n: int) -> int:
dp = [0 for _ in range(38)]
dp[1] = 1
dp[2] = 1
for i in range(3, n + 1):
dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3]
return dp[n]
todo:递归
csming1995 commented
Java解法:
class Solution {
public int tribonacci(int n) {
int[] topThree = new int[]{0, 1, 1};
if (n < 3) return topThree[n];
for (int i = 3; i <= n; i++) {
int temp = topThree[0] + topThree[1] + topThree[2];
topThree[0] = topThree[1];
topThree[1] = topThree[2];
topThree[2] = temp;
}
return topThree[2];
}
}
JalanJiang commented
import functools
class Solution:
@functools.lru_cache(None)
def tribonacci(self, n: int) -> int:
if n == 0:
return 0
if n == 1:
return 1
if n == 2:
return 1
return self.tribonacci(n - 3) + self.tribonacci(n - 2) + self.tribonacci(n - 1)