leetcode:70 Climbing Stairs-每日編程第十五題

Climbing Stairs

Total Accepted: 83180 Total Submissions: 234611 Difficulty: Easy

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?

思路:

很容易想到用遞歸。但是遞歸重複計算,耗時,耗內存。

因此,就改用循環來計算。n節階梯的方法數等(n-1)節階梯的方法數(最後跨一步)+(n-2)節階梯的方法數(最後跨兩步)。

class Solution {
public:
    int climbStairs(int n) {
        if(n==1){
            return 1;
        }else if(n==2){
            return 2;
        }
        int num1=1;
        int num2=2;
        int num3;
        for(int i=3;i<=n;i++){
            num3=num1+num2;
            num1=num2;
            num2=num3;
        }
        return num3;
    }
};

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