1137:第 N 个泰波那契数

This commit is contained in:
huangge1199@hotmail.com 2021-08-08 22:23:50 +08:00
parent 4a59c75507
commit 4223806fbc
3 changed files with 99 additions and 1 deletions

View File

@ -0,0 +1,66 @@
//泰波那契序列 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
//
// Related Topics 记忆化搜索 数学 动态规划
// 👍 115 👎 0
package leetcode.editor.cn;
//1137: N 个泰波那契数
class NThTribonacciNumber {
public static void main(String[] args) {
//测试代码
Solution solution = new NThTribonacciNumber().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int tribonacci(int n) {
if (n == 0) {
return 0;
}
if (n <= 2) {
return 1;
}
int p = 0, q = 0, r = 1, s = 1;
for (int i = 3; i <= n; ++i) {
p = q;
q = r;
r = s;
s = p + q + r;
}
return s;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,32 @@
<p>泰波那契序列&nbsp;T<sub>n</sub>&nbsp;定义如下:&nbsp;</p>
<p>T<sub>0</sub> = 0, T<sub>1</sub> = 1, T<sub>2</sub> = 1, 且在 n &gt;= 0&nbsp;的条件下 T<sub>n+3</sub> = T<sub>n</sub> + T<sub>n+1</sub> + T<sub>n+2</sub></p>
<p>给你整数&nbsp;<code>n</code>,请返回第 n 个泰波那契数&nbsp;T<sub>n </sub>的值。</p>
<p>&nbsp;</p>
<p><strong>示例 1</strong></p>
<pre><strong>输入:</strong>n = 4
<strong>输出:</strong>4
<strong>解释:</strong>
T_3 = 0 + 1 + 1 = 2
T_4 = 1 + 1 + 2 = 4
</pre>
<p><strong>示例 2</strong></p>
<pre><strong>输入:</strong>n = 25
<strong>输出:</strong>1389537
</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ul>
<li><code>0 &lt;= n &lt;= 37</code></li>
<li>答案保证是一个 32 位整数,即&nbsp;<code>answer &lt;= 2^31 - 1</code></li>
</ul>
<div><div>Related Topics</div><div><li>记忆化搜索</li><li>数学</li><li>动态规划</li></div></div>\n<div><li>👍 115</li><li>👎 0</li></div>

File diff suppressed because one or more lines are too long