leet-code/src/main/java/leetcode/editor/cn/NThTribonacciNumber.java

66 lines
1.4 KiB
Java
Raw Normal View History

2021-08-08 22:23:50 +08:00
//泰波那契序列 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)
}