leetcode70[Climbing stairs]

爬樓梯問題,描述如下:

You are climbing a staircase. 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層共有多少種爬法。這是一道動態規劃問題,設爬到第i層共有d[i]種爬法,因爲一次能爬一層或兩層,所以爬到第i層可以從i-1層爬一層和i-2層爬兩層,即d[i] = d[i-1]+d[i-2],且d[1]=1,d[2]=2,這點和斐波那契數列完全一致,代碼如下。

class Solution {
public:
    int climbStairs(int n) {
        int s1 = 1;
        int s2 = 1;
        for(int i = 1;i < n;++i)
        {            
            s2 = s1+s2;
            s1 = s2-s1; 
        }
        return s2;
    }
};

 

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