ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

letecode [70] - Climbing Stairs

2019-06-06 10:48:46  阅读:405  来源: 互联网

标签:arr int top step steps 70 Climbing climb 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?

Note: Given n will be a positive integer.

Example 1:

Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps

Example 2:

Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step

题目大意:

  有n阶楼梯,可一次爬一阶或两阶,求共多少种爬法。

理  解 :

  n=0时,爬法=0;n=1时,爬法=1;n=2时,可爬2两次一阶、或一次两阶,爬法=2;

  从n=3开始,设爬法为f,则f(n) = f(n-1) + f(n-2);表示n阶阶梯的爬法等于当前爬一阶的种类+当前爬两阶的种类。

代 码 C++: 

class Solution {
public:
    int climbStairs(int n) {
        int *arr = new int[n+1];
        if(n==1 || n==2) return n;
        arr[0] = 0;
        arr[1] = 1;
        arr[2] = 2;
        int i;
        for(i=3;i<=n;++i){
            arr[i] = arr[i-1] + arr[i-2];
        }
        return arr[n];
    }
};

运行结果:

  执行用时 : 4 ms  内存消耗 : 8.5 MB

标签:arr,int,top,step,steps,70,Climbing,climb,Stairs
来源: https://www.cnblogs.com/lpomeloz/p/10983623.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有