-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
Copy path1137-n-th-tribonacci-number.cs
78 lines (69 loc) · 1.38 KB
/
1137-n-th-tribonacci-number.cs
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
// iterative with no array
public class Solution
{
public int Tribonacci(int n)
{
int seq1 = 0;
int seq2 = 0;
int seq3 = 1;
for (int i = 0; i < n; i++)
{
int seq2_temp = seq2;
seq2 += seq3;
seq3 = seq2_temp;
int seq1_temp = seq1;
seq1 += seq2;
seq2 = seq1_temp;
}
return seq1;
}
}
// bottom up solution
public class Solution
{
public int Tribonacci(int n)
{
if (n <= 0)
{
return 0;
}
else if (n <= 2)
{
return 1;
}
var dp = new int[n];
dp[0] = 1;
dp[1] = 1;
dp[2] = 2;
for (int i = 3; i < n; i++)
{
dp[i] = dp[i - 3] + dp[i - 2] + dp[i - 1];
}
return dp[n - 1];
}
}
// recursive + memo solution
public class Solution
{
public int Tribonacci(int n)
{
int[] mem = new int[n];
return Recursive(n, mem);
}
private int Recursive(int n, int[] mem)
{
if (n <= 0)
{
return 0;
}
else if (n == 1)
{
return 1;
}
else if (mem[n - 1] == 0)
{
mem[n - 1] = Recursive(n - 1, mem) + Recursive(n - 2, mem) + Recursive(n - 3, mem);
}
return mem[n - 1];
}
}