Recursion on staircase

后端 未结 4 1736
[愿得一人]
[愿得一人] 2021-01-03 14:08

I\'m trying to understand the solution provided in a book to the following question:

\"A child is running up a staircase with n steps and can hop either 1 step, 2 st

4条回答
  •  盖世英雄少女心
    2021-01-03 15:13

    You need to think about it has a tree with 3 possible options on each node. If the size of the staircase is 4 we will have something like this:

    (4)--1-->(3)--..(Choose a step and keep branching)...
      |__2-->(2)--..(Until you get size of zero)............
      |__3-->(1)--1-->(0) # <--Like this <--
    

    At the end if you count all the leafs with size of zero you will get all the possible ways.

    So you can think it like this, what if you take a step and then consider update the size of the stair like this size-step, where your steps can be (1,2,3)

    Doing that you can code something like this:

    choices = (1, 2, 3)
    counter = 0
    
    def test(size):
        global counter
    
        if size == 0:
            counter += 1
    
        for choice in choices:
            if size - choice >= 0:
                test(size - choice)
    
        return counter
    

提交回复
热议问题