1. Naive Recursion
Intuition
Branch at each step by either taking 1 step or 2 steps until n is reached.
Algorithm
- Define
climb(n). - If
n <= 2, returnn. - Return
climb(n - 1) + climb(n - 2).
#include <iostream> using namespace std; int climbStairsRec(int n) { if (n <= 2) return n; return climbStairsRec(n - 1) + climbStairsRec(n - 2);} int main() { int n = 4; cout << "Ways to climb " << n << " stairs (Recursive): " << climbStairsRec(n) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(2^n) - Space complexity:
O(n) recursion call stack