Print ways to reach the n’th stair

让人想犯罪 __ 提交于 2021-02-07 20:32:31

问题


I recently encountered this problem in an interview

There are n stairs, a person standing at the bottom wants to reach the top. The person can climb either 1 stair or 2 stairs at a time.

Print all possible ways person can reach the top.

For example, n=4 Output:

1 2 3 4
1 2 4
1 3 4
2 3 4
2 4

But I couldn't code this properly. How to code up solution for this?


回答1:


To print the number of ways, you can first understand how to calculate the number of ways, and adjust it so each "count" will print instead of just count:

D(0) = 1
D(-1) = 0
D(i) = D(i-1) + D(i-2)

To adjust it to actual printing, you need to "remember" the choices you have made, and follow the same logic. Pseudo code:

printWays(curr, n, soFar):
   if curr > n: 
      return
   soFar.append(curr)
   if n == curr:
      print soFar
      soFar.removeLast()
      return
   printWays(curr+1,n,soFar)
   printWays(curr+2,n,soFar)
   soFar.removeLast()

The idea is:

  • soFar is the current series of steps you did.
  • curr is the current step you're at.
  • n is the last stair you need to get to.
  • At each point, you either climb one stair or two. You check both options.



回答2:


You can try some recursive solution where you call recursively CanClimb(n-1) and CanClimb(n-2) to visualize the possible ways.

Sample solution in C#:

public static void ClimbWays(int n, int currentIndex, int[] currectClimb)
{
    if (n < 0) return;

    if (n == 0)
    {
        for (var i = currentIndex - 1; i >= 0; i--)
        {
            Console.Write(currectClimb[i] + " ");
        }

        Console.WriteLine();
        return;
    }

    currectClimb[currentIndex] = n;
    ClimbWays(n - 1, currentIndex + 1, currectClimb);
    ClimbWays(n - 2, currentIndex + 1, currectClimb);
}

Output for ClimbWays(4, 0, new int[4]);:

1 2 3 4
2 3 4
1 3 4
1 2 4
2 4

If you want to just count them you can use the well known Fibonacci sequence which can be calculated iteratively:

public static int Fibonacci(int n)
{
    int a = 0;
    int b = 1;
    // In N steps compute Fibonacci sequence iteratively.
    for (int i = 0; i < n; i++)
    {
        int temp = a;
        a = b;
        b = temp + b;
    }
    return a;
}


来源:https://stackoverflow.com/questions/32818911/print-ways-to-reach-the-n-th-stair

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!