Finding all paths down stairs?

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

    Great answer by @templatetypedef - I did this problem as an exercise and arrived at the Fibonacci numbers on a different route:

    The problem can basically be reduced to an application of Binomial coefficients which are handy for Combination problems: The number of combinations of n things taken k at a time (called n choose k) can be found by the equation

    enter image description here

    Given that and the problem at hand you can calculate a solution brute force (just doing the combination count). The number of "take 2 steps" must be zero at least and may be 50 at most, so the number of combinations is the sum of C(n,k) for 0 <= k <= 50 ( n= number of decisions to be made, k = number of 2's taken out of those n)

    BigInteger combinationCount = 0;
    for (int k = 0; k <= 50; k++)
    {
        int n = 100 - k;
        BigInteger result = Fact(n) / (Fact(k) * Fact(n - k));
        combinationCount += result;
    }
    

    The sum of these binomial coefficients just happens to also have a different formula:

    enter image description here

提交回复
热议问题