We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 797f1f6 commit ad20963Copy full SHA for ad20963
24 - Dynamic Programming Problems/01 - Example | Nth Fibonacci Number/01 - Recursive Approach.cpp
@@ -1,8 +1,14 @@
1
class Solution {
2
public:
3
int nthFibonacci(int n) {
4
- if(n == 0 || n == 1) return n;
5
-
6
- return nthFibonacci(n-1) + nthFibonacci(n-2);
+ // Base case: If n is 0 or 1, return n directly.
+ // F(0) = 0 and F(1) = 1 are the first two terms of the Fibonacci sequence.
+ if (n == 0 || n == 1)
7
+ return n;
8
+
9
+ // Recursive case:
10
+ // The nth Fibonacci number is the sum of the (n-1)th and (n-2)th Fibonacci numbers.
11
+ // Recursively calculate the values for smaller subproblems.
12
+ return nthFibonacci(n - 1) + nthFibonacci(n - 2);
13
}
14
};
0 commit comments