-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path509. Fibonacci-Number.java
62 lines (47 loc) · 1012 Bytes
/
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
// https://leetcode.com/problems/fibonacci-number/description/
// brute force method
class Solution {
public int fib(int n) {
int f=0;
int l=1;
int i=0;
int sum=0;
if(n<=1) return n;
while(n-1>i){
sum=f+l;
f=l;
l=sum;
i++;
}
return sum;
}
}
// recursive method
// The Rule is xn = xn−1 + xn−2
class Solution {
public int fib(int n) {
if(n<=1) return n;
return fib(n-1)+fib(n-2);
}
}
// applying DP
// it beats 100%
class Solution {
public int fib(int n) {
int[] dpArray=new int[n+1];
Arrays.fill(dpArray,-1);
return halper(n,dpArray);
}
public int halper(int n, int[] array){
if(n==1||n==0){
return n;
}
if(array[n]!=-1){
return array[n];
}
int a= halper(n-1,array);
int b=halper(n-2,array);
array[n]=a+b;
return a+b;
}
}