zoukankan      html  css  js  c++  java
  • [LeetCode] 1137. N-th Tribonacci Number

    Description

    e 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.

    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.

    Analyse

    类似于fibonacci,由两项的递推变成了三项,也就是tribonacci

    T0 = 0

    T1 = 1

    T2 = 1

    Tn+3 = Tn + Tn+1 + Tn+2

    构造一个递推公式,直接用递归来做,写起来很简单,可是超时了,原因是很多数据重复计算了

    int tribonacci(int n) {
        if (n == 0 || n == 1) return n;
        if (n == 2) return 1;
    
        return tribonacci(n-3) + tribonacci(n-2) + tribonacci(n-1);
    }
    

    改用动态规划的思想,AC了

    int tribonacci(int n) {
        int list[38] = {0, 1, 1,};
        if (n < 3) return list[n];
    
        for (int i = 3; i <= n; i++)
        {
            list[i] = list[i-3] + list[i-2] + list[i-1];
        }
    
        return list[n];
    }
    

    但还是比LeetCode上其他代码要慢,看了下更快的代码,唯一的差别就是把数组换成了vector

    int tribonacci(int n) {
        vector<int> list(38);
        int *list = (int*)malloc(sizeof(int) * 38); // 速度和数组一样,也比vector慢
        list[0] = 0;
        list[1] = 1;
        list[2] = 1;
    
        for (int i = 3; i <= n; i++)
        {
            list[i] = list[i-3] + list[i-2] + list[i-1];
        }
    
        return list[n];
    }
    
  • 相关阅读:
    ElasticSearch集群设置
    NEST与JSON语法对照 一 match与multi_match
    某墙尼妹,用个Response.Filter来解决StackExchange.Exceptional中google cdn的问题
    高频
    Linux 后台执行命令
    Mysql 常用函数汇总
    Golang 昨天、今天和明天
    Golang——Cron 定时任务
    Golang 资料整理
    Golang: for range
  • 原文地址:https://www.cnblogs.com/arcsinw/p/11425701.html
Copyright © 2011-2022 走看看