File tree Expand file tree Collapse file tree 1 file changed +77
-0
lines changed Expand file tree Collapse file tree 1 file changed +77
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ * @lc app=leetcode id=509 lang=java
3
+ *
4
+ * [509] Fibonacci Number
5
+ *
6
+ * https://leetcode.com/problems/fibonacci-number/description/
7
+ *
8
+ * algorithms
9
+ * Easy (66.65%)
10
+ * Total Accepted: 39.3K
11
+ * Total Submissions: 58.7K
12
+ * Testcase Example: '2'
13
+ *
14
+ * The Fibonacci numbers, commonly denoted F(n) form a sequence, called the
15
+ * Fibonacci sequence, such that each number is the sum of the two preceding
16
+ * ones, starting from 0 and 1. That is,
17
+ *
18
+ *
19
+ * F(0) = 0, F(1) = 1
20
+ * F(N) = F(N - 1) + F(N - 2), for N > 1.
21
+ *
22
+ *
23
+ * Given N, calculate F(N).
24
+ *
25
+ *
26
+ *
27
+ * Example 1:
28
+ *
29
+ *
30
+ * Input: 2
31
+ * Output: 1
32
+ * Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.
33
+ *
34
+ *
35
+ * Example 2:
36
+ *
37
+ *
38
+ * Input: 3
39
+ * Output: 2
40
+ * Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.
41
+ *
42
+ *
43
+ * Example 3:
44
+ *
45
+ *
46
+ * Input: 4
47
+ * Output: 3
48
+ * Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.
49
+ *
50
+ *
51
+ *
52
+ *
53
+ * Note:
54
+ *
55
+ * 0 ≤ N ≤ 30.
56
+ *
57
+ */
58
+ class Solution {
59
+ public int fib (int n ) {
60
+ if (n <= 0 ) return 0 ;
61
+ if (n == 1 ) return 1 ;
62
+ if (n == 2 ) return 1 ;
63
+
64
+ int one_step_before = 1 ;
65
+ int two_steps_before = 1 ;
66
+ int result = 0 ;
67
+
68
+ for (int i = 2 ; i < n ; i ++) {
69
+ result = one_step_before + two_steps_before ;
70
+ two_steps_before = one_step_before ;
71
+ one_step_before = result ;
72
+ }
73
+
74
+ return result ;
75
+ }
76
+ }
77
+
You can’t perform that action at this time.
0 commit comments