新博文地址:[leetcode]Climbing Stairs
http://oj.leetcode.com/problems/climbing-stairs/
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?
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
是不是很熟悉?跟青蛙上台阶一样一样滴。。。菲波那切数列,不罗嗦
两种方法:
1. 递归(大量冗余计算,可能超时)
2. 循环
public int climbStairs(int n) {
if (n == 0 || n == 1) {
return 1;
}
int[] array = new int[n + 1];
array[1] = 1;
array[2] = 2;
for (int i = 3; i <= n; i++) {
array[i] = array[i-1] + array[i-2];
}
return array[n];
}

本文探讨了经典的爬楼梯问题,通过对比青蛙跳台阶问题,介绍了使用斐波那契数列求解的不同方法,包括递归(可能超时)及循环方式,并给出了具体的Java代码实现。
759

被折叠的 条评论
为什么被折叠?



