LeetCode: Climbing Stairs [070]

来源:互联网 发布:循环大批量更新数据库 编辑:程序博客网 时间:2024/06/05 05:58

【题目】



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阶,为爬到梯子顶共有多少种爬法


【思路】

       

依次确定跳到每一阶上的爬法数目
这其实是一个斐波那契数列数列。假设A[i]表示爬到第i阶的爬法数
当i=1时,A[1]=1    (从梯子底只要爬一阶即可)
当i=2时,A[2]=2    (从第一阶往上再爬一阶,或者从梯子底直接爬谅解,所以是两种爬法)
当i>=3时,A[i]=A[i-1]+A[i-2]    (因为每次只能爬一阶或者两阶,因此要跳到当前阶,只可能从他的前一阶或者前前一阶往上爬)


【代码】

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


0 0
原创粉丝点击