Leetcode10: Climbing Stairs

来源:互联网 发布:淘宝商家联盟 编辑:程序博客网 时间:2024/06/06 14:15

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?

思路很简单,一个台阶的时候需要1步,只有一种方法;两个台阶的时候可以分为两次一步或者一次两步,有2种方法;n个台阶的时候可以分为2步+n-2个台阶或者1步+n-1个台阶。

class Solution {public:    int climbStairs(int n) {        switch (n){        case 0:            return 0;        case 1:            return 1;        case 2:            return 2;        default:            return climbStairs(n-1) + climbStairs(n-2);         }    }};
我先运用了递归的思想,结果报错超时,这样做确实很耗时。后来想想这不就是类似斐波那契数列吗?

class Solution {public:    int climbStairs(int n) {       int a = 1;       int b = 2;       int c = 0;       if(n == 0)       return c;       else if(n == 1)       return a;       else if(n == 2)       return b;              for(int i = 2; i < n; i++)       {           c = a + b;           a = b;           b = c;       }       return c;    }};



0 0
原创粉丝点击