动态思想的简单题,直接版本是创建一个动态数组存储;
优化版本是只保存最终的结果;空间复杂度从O(n) 减到O(1);
class Solution: def tribonacci(self, n: int) -> int: if n<2: return n if n == 2: return 1 dp = [0] * (n+1) dp[0] = 0 dp[1] = 1 dp[2] = 1 for i in range(3, n+1): dp[i] = dp[i-3] + dp[i-2] + dp[i-1] return dp[n]