-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy path509. Fibonacci Number.java
executable file
·120 lines (97 loc) · 2.33 KB
/
509. Fibonacci Number.java
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
E
tags: Math, DP, Memoization
#### Memoization
- fib[n] = fibonacci(n - 1) + fibonacci(n - 2);
#### DP array.
- 滚动数组, 简化DP
#### recursively calculate
- recursively calculate fib(n - 1) + fib(n - 2). 公式没问题, 但是时间太长, timeout.
```
/*
Find the Nth number in Fibonacci sequence.
A Fibonacci sequence is defined as follow:
The first two numbers are 0 and 1.
The i th number is the sum of i-1 th number and i-2 th number.
The first ten numbers in Fibonacci sequence is:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ...
Example
Given 1, return 0
Given 2, return 1
Given 10, return 34
Note
The Nth fibonacci number won't exceed the max value of signed 32-bit integer in the test cases.
Tags Expand
Enumeration Mathematics Non Recursion
*/
// Memoization
class Solution {
int[] fib = null;
public int fibonacci(int n) {
if (fib == null) {
fib = new int[n + 1];
}
if (n <= 2) {
return n - 1;
}
if (fib[n] != 0) {
return fib[n];
}
return fib[n] = fibonacci(n - 1) + fibonacci(n - 2);
}
}
/*
Recap 3.28.2016.
Rolling array, instead of initiating array.
*/
class Solution {
public int fibonacci(int n) {
if (n <= 1) {
return 0;
}
int first = 0;
int second = 1;
for (int i = 2; i < n; i++) {
int temp = second;
second = first + second;
first = temp;
}
return second;
}
}
/*
Thoughts:
Bottomup with for loop.
1. If non-recursion, do for loop for that n
2. Note: this specfiic problem is not 0-based. it's 1-based.
3. return fib[n]
*/
class Solution {
public int fibonacci(int n) {
if (n <= 1) {
return 0;
}
int[] fib = new int[n];
fib[0] = 0;
fib[1] = 1;
for (int i = 2; i < n; i++) {
fib[i] = fib[i - 1] + fib[i - 2];
}
return fib[n - 1];
}
}
/*
Recursive. Long time complexity
Timeout
*/
class Solution {
public int fibonacci(int n) {
if (n <= 1) {
return 0;
}
if (n == 2) {
return 1;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
```