41-Climbing Stairs-leetcode

  1. Climbing Stairs My Submissions QuestionEditorial Solution
    Total Accepted: 106498 Total Submissions: 290003 Difficulty: Easy
    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?

思路:so easy
重要的是思路清晰,对于n阶楼梯,可能由n-1阶迈上来的,也可能由n-2阶楼梯迈上来的,

f(n)n
f(n)=f(n1)+f(n2)
f(2)=2,f(1)=1

就是一斐波纳挈数列,通项和为
an=15((1+52)n(152)n)

这里的f(n)=an+1
这里程序有三种实现方式,递归效率最差,自底向上循环其次,最好的是常数级,用公式

class Solution {
public:
    int climbStairs(int n) {
        vector<int> vec(n+1,0);
        vec[1]=1;vec[2]=2;
        if(n<=2)return vec[n];
        for(int i=3;i<=n;++i)
            vec[i]=vec[i-1]+vec[i-2];
        return vec[n];
    }
};
原文地址:https://www.cnblogs.com/freeopen/p/5482926.html