LeetCode - 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?

http://oj.leetcode.com/problems/climbing-stairs/


Solution:

Simple dp. We know that if there is one stair, we have one way, if there are two stairs, we have two ways.

So assume we have step[n] ways for n stairs, and for n+1 stairs, step[n+1] = step[n] + step[n-1]. We can use step[n] + 1 or step[n-1] + 2.

Does this formula seem similar? Sure it is Fibonacci number!!!

So I just provide the iterative way for this problem. 

https://github.com/starcroce/leetcode/blob/master/climbing_stairs.cpp

//8 ms for 45 test cases
class Solution {
public:
    int climbStairs(int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int a = 1, b = 2;
        if(n == 1) {
            return a;
        }
        if(n == 2) {
            return b;
        }
        int c;
        for(int i = 3; i <= n; i++) {
            c = a + b;
            a = b;
            b = c;
        }
        return c;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章