Skip to content

Commit e25f11d

Browse files
committed
Add 509. Fibonacci Number recursive solution
1 parent 1900ff9 commit e25f11d

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

LeetCode/FibonacciNumber.cs

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Text;
4+
5+
namespace LeetCodeSolutionsLib
6+
{
7+
/// <summary>
8+
/// 509. Fibonacci Number
9+
/// The Fibonacci numbers, commonly denoted to F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of two preceeding ones, start from 0 and 1.
10+
/// IE) Input : [4]
11+
/// Output : [3]
12+
/// Explanation: F(4) = F(3) + F(2) ==> 2 + 1 = 3
13+
/// </summary>
14+
public class FibonacciNumber : Solution
15+
{
16+
private int n;
17+
18+
public FibonacciNumber(int n)
19+
{
20+
this.n = n;
21+
}
22+
23+
private int fib(int n)
24+
{
25+
// Base cases
26+
int result = 0;
27+
if (n == 0) return result;
28+
if (n == 1 || n == 2)
29+
{
30+
result = 1;
31+
}
32+
// Otherwise use recursion to calculate the Fibonacci Number
33+
else
34+
{
35+
result = fib(n - 1) + fib(n - 2);
36+
}
37+
return result;
38+
}
39+
40+
public override void PrintExample()
41+
{
42+
var watch = System.Diagnostics.Stopwatch.StartNew();
43+
var results = fib(this.n);
44+
watch.Stop();
45+
Console.WriteLine($"509. Fibonacci Number\n" +
46+
$"Input Num = {this.n} \n" +
47+
$"Result: [{results}] \n" +
48+
$"Execution Speed: {watch.ElapsedMilliseconds}ms \n");
49+
}
50+
}
51+
}

LeetCodeConsoleApp/Program.cs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,13 @@ static void Main(string[] args)
152152

153153
#endregion
154154

155+
#region 509. Fibonacci Number
156+
157+
FibonacciNumber fibonacciNumber = new FibonacciNumber(10);
158+
fibonacciNumber.PrintExample();
159+
160+
#endregion
161+
155162
#region 622. MyCircularQueue
156163

157164
MyCircularQueue myCircularQueue = new MyCircularQueue(1);

0 commit comments

Comments
 (0)