-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1137.n-th-tribonacci-number.go
More file actions
124 lines (112 loc) · 1.97 KB
/
1137.n-th-tribonacci-number.go
File metadata and controls
124 lines (112 loc) · 1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
/*
* @lc app=leetcode id=1137 lang=golang
*
* [1137] N-th Tribonacci Number
*
* https://leetcode.com/problems/n-th-tribonacci-number/description/
*
* algorithms
* Easy (55.96%)
* Likes: 317
* Dislikes: 41
* Total Accepted: 44.6K
* Total Submissions: 79.8K
* Testcase Example: '4'
*
* The 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.
*
*/
// @lc code=start
func tribonacci(n int) int {
return tribonacci4(n)
}
// dynamic program, using three element to store cache data
func tribonacci4(n int) int {
if n == 0 {
return 0
} else if n == 1 || n == 2 {
return 1
}
dp0, dp1, dp2, dpn := 0, 1, 1, 0
for i := 3; i <= n; i++ {
dpn = dp0 + dp1 + dp2
dp0, dp1, dp2 = dp1, dp2, dpn
}
return dpn
}
// dynamic program, using array, n+1 size
func tribonacci3(n int) int {
if n == 0 {
return 0
} else if n == 1 || n == 2 {
return 1
}
dp := map[int]int{}
dp[0] = 0
dp[1] = 1
dp[2] = 1
for i := 3; i <= n; i++ {
dp[i] = dp[i-3] + dp[i-2] + dp[i-1]
}
return dp[n]
}
// recusive with memory
func tribonacci2(n int) int {
hash := map[int]int{}
return helper(n, hash)
}
func helper(n int, hash map[int]int) int {
if v, ok := hash[n]; ok {
return v
}
sum := 0
if n == 0 {
sum = 0
} else if n == 1 || n == 2 {
sum = 1
} else {
sum = helper(n-1, hash) + helper(n-2, hash) + helper(n-3, hash)
}
hash[n] = sum
return sum
}
// cursive, time limit exceeded
func tribonacci1(n int) int {
if n == 0 {
return 0
} else if n == 1 || n == 2 {
return 1
}
return tribonacci1(n-1) + tribonacci1(n-2) + tribonacci1(n-3)
}
// @lc code=end