您的位置:首页 > 大数据 > 人工智能

LeetCode-Climbing Stairs(爬楼梯问题)

2017-11-21 20:35 537 查看
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?

这道题跟斐波那契数列非常相似,俗称青蛙跳台阶问题,青蛙只能跳1层或者2层,台阶有n层,那么青蛙只能从n-1台阶跳上去或者从n-2台阶跳上去,这时候很容易想到递归公式sum
= sum[n-1]+sum[n-2]。

第一种方法,使用递归,但效率很低。

public int climbStairs1(int n) {
if (n == 1 || n == 2) {
return n;
}
return climbStairs1(n-1) + climbStairs1(n-2);
}

在说第二种方法前,考虑一下5级台阶的问题,如果用递归的方法来做,可画出递归图如下。



动态规划的思想就是把重叠子问题存储下来,下次调用直接查表即可。比如在第一次递归调用时,n=3已经将结果计算出来,在n=4的时候就不需要就算了。

public class Solution {
public int climbStairs(int n) {
if(n<=2) return n;
int[] a = new int[n+1];
a[1] = 1;
a[2] = 2;
for(int i=3; i<=n; i++) {
a[i] = a[i-1] + a[i-2];
}
return a
;
}
}

参考:
http://blog.csdn.net/my_jobs/article/details/43535179
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: