LeetCode No.70 Climbing Stairs

深入理解并灵活运用fibonacci数列
1、思路:

最后一步分两种情况:走一个台阶或走两个台阶,此时问题转化为走最后一步前有多少种情况,即走n-1和 n-2 个台阶有多少种情况。

2、使用递归

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

结果:Time Limit Exceeded

3、使用数组

class Solution {
public:
    int climbStairs(int n) {
        int num[10000];
        num[0]=1;
        num[1]=2;
        for(int i=2;i
4、其它解法

public int climbStairs(int n) {
    // base cases
    if(n <= 0) return 0;
    if(n == 1) return 1;
    if(n == 2) return 2;
   
    int one_step_before = 2;
    int two_steps_before = 1;
    int all_ways = 0;
   
    for(int i=2; i
体会: two_steps_before、one_step_before和all_ways是相邻的三步,所以在求得新的all_ways后, two_steps_before、one_step_before 再各自向后移动一位。

你可能感兴趣的:(LeetCode)