Climbing Stairs
/**
*
* <p>
* ClassName ClimbingStairs
* </p>
* <p>
* Description You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps.
* In how many distinct ways can you climb to the top?
* </p>
*
* @author TKPad wangx89@126.com
* <p>
* Date 2015年3月19日 下午9:18:24
* </p>
* @version V1.0.0
*
*/
public class ClimbingStairs {
public int climbStairs(int n) {
if (n <= 0) {
return 0;
}
// n步到顶,在n步中,你能够走一步或者两步。一共同拥有多少种走法
if (1 == n || 2 == n) {// 一级台阶,仅仅有一种走法
// 两级台阶,有两种走法
return n;
}
return climbStairs(n - 1) + climbStairs(n - 2);// 这样做超时
}
public int climbStairs2(int n) {
int[] num = new int[n + 1];
num[0] = 1;
num[1] = 1;
for (int i = 2; i <= n; i++) {
num[i] = num[i - 1] + num[i - 2];
}
return num[n];// 这样就不会超时了
}
public static void main(String[] args) {
long start = System.currentTimeMillis();
// System.out.println(new ClimbingStairs().climbStairs(26));
System.out.println(new ClimbingStairs().climbStairs2(45));
long end = System.currentTimeMillis();
System.out.println(end - start);
}
}