70. Climbing Stairs

来源:互联网 发布:画漫画的软件 编辑:程序博客网 时间:2024/06/10 07:47

题目:

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?


题意:

你在爬楼梯的情景下,到顶端需要n步。每次你可以爬1或2步,问一共有多少种独立互不相同的爬到顶端的方式?


思路一:

题目要求与斐波那契数列非常相似,可以直接利用递归实现。

斐波那契数列:指的是这样一个数列 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368。这个数列从第2项开始,每一项都等于前两项之和。

代码:C++版:Time Limit Exceeded 超时,因为做了很多没有意义的分支计算

class Solution {public:    int climbStairs(int n) {        if (n <= 0) return 0;        if (n == 1 || n == 2) return n;        return climbStairs(n-1) + climbStairs(n-2);    }};


思路二:

动态规划实现,给定的楼梯有n阶,因为每次只能爬1步或者2步,所以爬到第n阶的方法,只能要么是从n-1阶上爬1步到的,要么是从n-2阶上爬2步到的,所以动态规划递推公式为dp[n] = dp[n-1] + dp[n-2];

代码:C++版:0ms

class Solution {public:    int climbStairs(int n) {        vector<int> res(n+1);        res[0] = 1;        res[1] = 1;        for (int i=2; i<=n; ++i) {            res[i] = res[i-1] + res[i-2];        }        return res[n];    }};

0 0
原创粉丝点击