LeetCode知识点总结 - 1137

LeetCode 1137. N-th Tribonacci Number

考点难度
Dynamic ProgrammingEasy
题目

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.

思路

先设定每个值都是-1(un-calculated)。如果n位置上不是-1,返回那个值,否则通过斐波那契数列的计算公式用前三位数字算出n位置的数。

答案
class Solution {
    int[] memo;
    
    Solution() {
        // Initialize memo, with -1 as flags for not calculated
        memo = new int[38]; // 0 through 37
        memo[0] = 0;
        memo[1] = 1;
        memo[2] = 1;
        for(int i = 3; i < memo.length; i++) memo[i] = -1;
    }
    
    public int tribonacci(int n) {
        // If we have already calculated value, return it.
        if(memo[n] != -1) {
            return memo[n];
        }
        else {
            int result = tribonacci(n-3) + tribonacci(n-2) + tribonacci(n-1);
            memo[n] = result;
            return result;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值