Skip to content

1137. 第 N 个泰波那契数 #62

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
buuing opened this issue Nov 15, 2021 · 0 comments
Open

1137. 第 N 个泰波那契数 #62

buuing opened this issue Nov 15, 2021 · 0 comments

Comments

@buuing
Copy link
Owner

buuing commented Nov 15, 2021

泰波那契序列 Tn 定义如下: 

T0 = 0, T1 = 1, T2 = 1, 且在 n >= 0 的条件下 Tn+3 = Tn + Tn+1 + Tn+2

给你整数 n,请返回第 n 个泰波那契数 Tn 的值。

 

示例 1:

输入:n = 4
输出:4
解释:
T_3 = 0 + 1 + 1 = 2
T_4 = 1 + 1 + 2 = 4

示例 2:

输入:n = 25
输出:1389537

提示:

  • 0 <= n <= 37
  • 答案保证是一个 32 位整数,即 answer <= 2^31 - 1。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/n-th-tribonacci-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。




  • 记忆化搜索
const tribonacci = n => {
  const memo = [0, 1, 1]
  const dfs = n => {
    if (memo[n] === void 0) {
      memo[n] = dfs(n - 1) + dfs(n - 2) + dfs(n - 3)
    }
    return memo[n]
  }
  return dfs(n)
}
  • 动态规划
const tribonacci = n => {
  const dp = [0, 1, 1]
  for (let i = 3; i <= n; i++) {
    dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3]
  }
  return dp[n]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant