মূল কনটেন্টে যান
🌍
গ্লোবাল DSA
প্যাটার্নটপিক 9 · Dynamic Programming

9.1 Fibonacci Style / Climbing Stairs

চিনবেন কীভাবে
dp[i] depends only on the previous 1–2 values — "how many ways to reach i"
Demo · approach · কোড — আগে নিজে চেষ্টা, আটকালে খুলুন

Demo: Climbing StairsLC 70 (Easy — Google/Amazon High)

Statement (Demo): A staircase has n steps and you climb 1 or 2 steps at a time. Return the number of distinct ways to reach the top. Example: n=33 (1+1+1, 1+2, 2+1) | ⚡ 1 ≤ n ≤ 45

Approach: Step i is reached from i-1 (one step) or i-2 (two steps), so dp[i] = dp[i-1] + dp[i-2]. Only the last two values matter, so space is O(1).

function climbStairs(n) {
  let prev = 1,
    cur = 1; // dp[0], dp[1]
  for (let i = 2; i <= n; i++) [prev, cur] = [cur, prev + cur];
  return cur;
}

Complexity: Time O(n), Space O(1)

Demo · Climbing Stairsplan · দিন ০০৫LC 70
নোট · ফাঁকা

প্রবলেম

  • (Hard — state = (position, last jump); Map-of-Sets memo)

    Statement: A frog crosses a river on stones (sorted positions). If its last jump was k, the next can be k-1, k or k+1; the first jump is 1. Return whether it can reach the last stone.
    Example: stones=[0,1,3,5,6,8,12,17]true | ⚡ stones.length ≤ 2000

    নোট · ফাঁকা