15.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?

Note: Given n will be a positive integer.

 

      题目要求给出有多少种不同的步伐爬上山顶。看似动态规划,但实际是一道fibonacci问题。设想一下,当n为0,结果为0;n为1,结果为1,n为2,结果为2(每次都走一步,或者一次走两步)。当要求n=k时,实际上只要把n[k-1]与n[k-2]相加就可得出结果n[k]

代码如下:

class Solution {
  public:
    int climbStairs(int n) {
      if(n<=0 || n==1 || n==2) return n;
      int mem[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];
    }
};

 

posted @ 2017-06-26 16:32  legooooo  阅读(128)  评论(0编辑  收藏  举报