Climbing Stairs Problem Solution with DP

🚀 Day 22/100 – DSA Challenge Today’s problem: Climbing Stairs (LeetCode | Easy | DP) The problem is simple: You can climb either 1 or 2 steps at a time. How many distinct ways are there to reach the top? 🔴 Approach 1: Recursion (Brute Force) 👉 At each step, you have 2 choices: Take 1 step Take 2 steps 📌 Java Code: class Solution { public int climbStairs(int n) { if (n <= 2) return n; return climbStairs(n - 1) + climbStairs(n - 2); } } ⚡ Complexity: Time: O(2ⁿ) ❌ (recomputes subproblems) Space: O(n) (recursion stack) 🟡 Approach 2: Memoization (Top-Down DP) 👉 Store results of subproblems to avoid recomputation 📌 Java Code: class Solution { public int climbStairs(int n) { int[] dp = new int[n + 1]; return helper(n, dp); } private int helper(int n, int[] dp) { if (n <= 2) return n; if (dp[n] != 0) return dp[n]; dp[n] = helper(n - 1, dp) + helper(n - 2, dp); return dp[n]; } } ⚡ Complexity: Time: O(n) ✅ Space: O(n) 🟢 Observation: This problem is essentially the Fibonacci sequence: f(n) = f(n-1) + f(n-2) 🎯 Key Learning: Start with recursion to understand the problem, then optimize using DP to eliminate overlapping subproblems. 📈 Day 22 done—getting better at recognizing DP patterns! #100DaysOfCode #DSA #DynamicProgramming #Java #CodingJourney

To view or add a comment, sign in

Explore content categories