[C++]LeetCode: 52 Climbing Stairs

题目:

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?

思路解析:

无法一下子判断是 Fibonacci number,于是开始分析问题。

the number of solutions for N steps stair(S[N]),可以由两部分组成,S[N-1] && S[N-2],由于剩下一步或者两步可以一次完成(题目要求)。则有S[N] = S[N-1] + S[N-2]。 由此联想到斐波那契数列

数学上,费波那契数列是以递归的方法来定义:

  • F_0=0
  • F_1=1
  • F_n = F_{n-1}+ F_{n-2}(n≧2)

用文字来说,就是费波那契数列由0和1开始,之后的费波那契系数就由之前的两数相加。首几个费波那契系数是(OEISA000045):

01123581321345589144233……

复杂度:O(N)

Attention:

1.注意循环的次数,N-2次;还有stepOne和stepTwo的初始值。

2.算法的精妙处,空间复杂度为常数,因为只使用了两个变量保存前两项的值,而不是用容器vector保存数列的全部值。

            ret = stepOne + stepTwo;    //S[N] = S[N-1] + S[N-2]
            stepTwo = stepOne;          //S[N-1]_new = S[N-2]_old
            stepOne = ret;              //S[N-2]_new = S[N]_old

AC Code:

class Solution {
public:
    int climbStairs(int n) {
        if(n == 0 || n == 1) return 1;
        //Fibonacci number 初始化
        int stepOne = 1, stepTwo = 1;
        int ret = 0;
        
        //Fibonacci number S[N] = S[N-1] + S[N-2]. stepOne计为S[N-1], stepTwo计为S[N-2],从第0项开始。统计N-2次。
        for(int i = 2; i <= n; i++)
        {
            ret = stepOne + stepTwo;    //S[N] = S[N-1] + S[N-2]
            stepTwo = stepOne;          //S[N-1]_new = S[N-2]_old
            stepOne = ret;              //S[N-2]_new = S[N]_old
        }
        
        return ret;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值