Climbing Stair爬楼梯算法详解

来源:互联网 发布:阿里巴巴农村淘宝兰西 编辑:程序博客网 时间:2024/06/01 17:22

问题详见: Climbing Stair

题目让我们求解一个n阶的楼梯每次上1步或者2步的情况下有多少种爬法。题目描述如下:
      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.

解题思路:

      由题可知,阶梯n为1时只有1种走法,n为2时为2种走法,以后n每增加1就会使得第一步走1还是2步的两种走法分别对应n-1和n-2阶的走法,即mem[i] = mem[i-1] + mem[i-2],显然这是斐波那序列。整个算法复杂度为O(n)。具体算法如下:

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

其提交运行结果如下:
Climbing Stairs

原创粉丝点击