by Long Luo
Personal blog Links
Recently to interview, in a small company interview, the company's small boss gave me an algorithm problem:
一个人爬楼梯,一步可以迈一级,二级,三级台阶,如果楼梯有N级,要求编写程序,求总共有多少种走法。
This question should be a very old topic, in the middle school mathematics, is one 排列组合问题
. At that time, after getting this topic, first think 递归
of the idea used to solve the problem:
N级楼梯问题可以划分为:N-1级楼梯,N-2级楼梯,N-3级楼梯的走法之和。
First calculate how many kinds of 0,1,2,3 and stairs are going:
1 --> 12 --> 11 23 --> 111 12 21 3
So, according to the above analysis, it is easy to write the following code:
public static int countNumber(int stepsNum) { int sum = 0; if (stepsNum == 0) { return 0; } if (stepsNum == 1) { return 1; } else if (stepsNum == 2) { return 2; } else if (stepsNum == 3) { return 4; } else if (stepsNum > 3) { return countNumber(stepsNum - 3) + countNumber(stepsNum - 2) + countNumber(stepsNum - 1); } return sum;}public static void main(String[] args) { for (int i = 0; i <= 10; i++) { System.out.println("楼梯台阶数:" + i + ", 走法有:" + countNumber(i)); }}
And look at the output:
楼梯台阶数:0, 走法有:0楼梯台阶数:1, 走法有:1楼梯台阶数:2, 走法有:2楼梯台阶数:3, 走法有:4楼梯台阶数:4, 走法有:7楼梯台阶数:5, 走法有:13楼梯台阶数:6, 走法有:24楼梯台阶数:7, 走法有:44楼梯台阶数:8, 走法有:81楼梯台阶数:9, 走法有:149
But how to solve the specific way?
But it is easy to figure out how many ways to go, based on this basis, how to output 具体的走法
it?
We can use Stack
the data structure and 递归
the idea to complete this topic:
Stack<T>用于保存每一步的走法。
The specific code looks like this:
/** * 一个人爬楼梯,一步可以迈一级,二级,三级台阶,如果楼梯有N级,编写程序,输出所有走法。 * * @param args */public static void main(String[] args) { Stack<Integer> stt = new Stack<Integer>(); buileT(stt, 3);}public static void buileT(Stack<Integer> stt, int N) { if (N >= 1) { stt.push(1); buileT(stt, N - 1); stt.pop(); } if (N >= 2) { stt.push(2); buileT(stt, N - 2); stt.pop(); } if (N >= 3) { stt.push(3); buileT(stt, N - 3); stt.pop(); } if (N == 0) { for (int i : stt) { System.out.print("Step:" + i + "-->"); } System.out.println("完成"); }}
Created by Long Luo in 2015-04-08 00:40:12 @Shenzhen, China.
completed by Long Luo in 2015-04-08 18:15:38 @Shenzhen, China.
Interview algorithm questions: Climb stairs, n stairs how many kinds of way?