★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-utkovtni-kt.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
The Tribonacci sequence Tn is defined as follows: git
T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0.github
Given n
, return the value of Tn. 微信
Example 1:oop
Input: n = 4 Output: 4 Explanation: T_3 = 0 + 1 + 1 = 2 T_4 = 1 + 1 + 2 = 4
Example 2:spa
Input: n = 25 Output: 1389537
Constraints:code
0 <= n <= 37
answer <= 2^31 - 1
.泰波那契序列 Tn 定義以下: htm
T0 = 0, T1 = 1, T2 = 1, 且在 n >= 0 的條件下 Tn+3 = Tn + Tn+1 + Tn+2blog
給你整數 n
,請返回第 n 個泰波那契數 Tn 的值。 three
示例 1:
輸入:n = 4 輸出:4 解釋: T_3 = 0 + 1 + 1 = 2 T_4 = 1 + 1 + 2 = 4
示例 2:
輸入:n = 25 輸出:1389537
提示:
0 <= n <= 37
answer <= 2^31 - 1
。1 class Solution { 2 func tribonacci(_ n: Int) -> Int { 3 var numbers = Array<Int>(repeating: 0, count: 38) 4 numbers[1] = 1 5 numbers[2] = 1 6 for i in 3..<38 { 7 numbers[i] = numbers[i-1] + numbers[i-2] + numbers[i-3] 8 } 9 return numbers[n] 10 } 11 }
4ms
1 class Solution { 2 func tribonacci(_ n: Int) -> Int { 3 if n == 0 { 4 return 0 5 } else if n == 1 { 6 return 1 7 } else if n == 2 { 8 return 1 9 } 10 var a = 0 11 var b = 1 12 var c = 1 13 var d = 0 14 for i in 3...n { 15 d = a + b + c 16 a = b 17 b = c 18 c = d 19 } 20 return d 21 } 22 }
8ms
1 class Solution { 2 func tribonacci(_ n: Int) -> Int { 3 var tribs = [Int](repeating: 0, count: max(n + 1, 3)) 4 tribs[0] = 0 5 tribs[1] = 1 6 tribs[2] = 1 7 guard n >= 3 else { 8 return tribs[n] 9 } 10 for i in 3...n { 11 tribs[i] = tribs[i - 1] + tribs[i - 2] + tribs[i - 3] 12 } 13 return tribs[n] 14 } 15 }
Runtime: 12 ms
1 class Solution { 2 func tribonacci(_ n: Int) -> Int { 3 var first:Int = 0 4 var second:Int = 1 5 var third:Int = 1 6 // here first,second and third are the previous three elements 7 switch n 8 { 9 case 0: 10 return 0 11 case 1,2: 12 return 1 13 default: 14 // if n=0 or n=1 then the tribonacci number is n itself 15 // else for loop will be executed 16 for i in 3...n 17 { 18 var newElement:Int = first + second + third 19 first=second 20 second=third 21 third=newElement 22 } 23 } 24 return third 25 } 26 }