awelgorithms

Climb-stairs recurrence

Updated

ways(n) = ways(n-1)+ways(n-2): last hop is a 1-step onto n or a 2-step onto n. Encode n as a = [n]. Bases: ways(0)=1, ways(1)=1 (or ways(1)=1, ways(2)=2 if you skip 0).

What to focus on

Do not write ways(n)=n. n=4 has 5 sequences. Count them. Memo or table; the naive tree is Fibonacci-shaped.

Worked examples

n=3

a = [3]
  1. ways(1)=1
  2. ways(2)=2
  3. ways(3)=2+1=3
  4. sequences 1+1+1, 1+2, 2+1

Result: 3

n=1

a = [1]
  1. only one single step
  2. base

Result: 1

n=2

a = [2]
  1. 1+1 and 2
  2. ways(2)=ways(1)+ways(0)=1+1

Result: 2

Try it

Write ways(n). n is a positive integer encoded as a = [n]. dp[i] is the number of 1-or-2 step sequences to climb i. Fill ways. Do not claim ways(n)=n after n=3. a = [1] → 1. [2] → 2. [3] → 3.

n is a positive integer ≥ 1. Steps are 1 or 2. ways(n) is the number of sequences.