Finding all paths down stairs?

后端 未结 13 1488
天命终不由人
天命终不由人 2020-12-13 07:21

I was given the following problem in an interview:

Given a staircase with N steps, you can go up with 1 or 2 steps each time. Output all possible way

13条回答
  •  粉色の甜心
    2020-12-13 08:14

    Your solution sounds right.

    S(n):
        If n = 1 return {1}
        If n = 2 return {2, (1,1)}
        Return S(n-1)x{1} U S(n-2)x{2}
    

    (U is Union, x is Cartesian Product)

    Memoizing this is trivial, and would make it O(Fib(n)).

提交回复
热议问题