您的位置:首页 > 其它

斐波那契数列之动态规划

2015-01-14 09:02 274 查看
有这样一道OJ

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?
https://oj.leetcode.com/problems/climbing-stairs/
咋一看不就是简单的斐波那契数列吗,递归就行了。

但是递归的话超时了。

于是用了动态规划

public class Solution {
    public int climbStairs(int n) {
        if(n==1) return 1;
        if(n==2) return 2;
        int pre = 1;
        int last = 2;
        for(int i=3; i<n; i++){
            int tmp = last;
            last +=  pre;
            pre = tmp;
        }
        return last + pre;
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: