Finding all paths down stairs?

后端 未结 13 1536
天命终不由人
天命终不由人 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:20

    You can generalize your recursive function to also take already made moves.

    void steps(n, alreadyTakenSteps) {
        if (n == 0) {
            print already taken steps
        }
        if (n >= 1) {
            steps(n - 1, alreadyTakenSteps.append(1));
        }
        if (n >= 2) {
            steps(n - 2, alreadyTakenSteps.append(2));
        }
    }
    

    It's not really the code, more of a pseudocode, but it should give you an idea.

提交回复
热议问题