You are climbing a staircase. It takes n steps to reach the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Example 1:
Input: n = 2 Output: 2 Explanation: There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps
Example 2:
Input: n = 3 Output: 3 Explanation: There are three ways to climb to the top. 1. 1 step + 1 step + 1 step 2. 1 step + 2 steps 3. 2 steps + 1 step
Constraints:
1 <= n <= 45Why this is a 1D Dynamic Programming problem
1D DP stores answers to sub-problems in a 1D array (or a few variables). Each dp[i] represents the answer to a sub-problem of size i. The solution to the full problem is built bottom-up from these smaller answers, eliminating the exponential redundancy of naive recursion.
Define dp[i] clearly ("what does it mean?"), identify the recurrence relation dp[i] = f(dp[i-1], dp[i-2], …), handle base cases.
Imagine you're climbing stairs. The number of ways to reach step n is ways(n-1) + ways(n-2). If you compute ways(n-1) and ways(n-2) independently by recursion, you recompute ways(1), ways(2), … dozens of times. DP caches them so each is computed exactly once.
From brute force to optimal — understand every step of the journey
The hardest part of DP is NOT the code — it's the definition of dp[i]. Ask yourself: "What is the sub-problem at index i?" Once that's crystal clear, the recurrence relation usually follows naturally. Common definitions: dp[i] = "max sum ending at i", "min cost to reach i", "number of ways to reach i". Write the definition as a comment before writing any code.