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 Stairs — LC 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=3 → 3 (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
নোট · ফাঁকা
প্রবলেম
- Frog Jumpplan · দিন ১০৮LC 403(Hard — state = (position, last jump); Map-of-Sets memo)
Statement: A frog crosses a river on
stones(sorted positions). If its last jump wask, the next can bek-1,kork+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নোট · ফাঁকা