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

Note: Given n will be a positive integer.


Example 1:

Input: 2
Output:  2
Explanation:  There are two ways to climb to the top.

1. 1 step + 1 step
2. 2 steps

Example 2:

Input: 3
Output:  3
Explanation:  There are three ways to climb to the top.

1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step

分析

        這道題其實是斐波那契數列的另一種表達方式,同時也可以利用動態規劃的思想來解答。由於一次可以選擇爬一級或兩級臺階,要想得到登上n級臺階的方法數f(n),則可以考慮登臺階的最後一步是爬一級還是兩級,也即登上臺階一共對應着兩種方式:f(n-1)和爬一級臺階;f(n-2)和爬兩級臺階。則很顯然,f(n)=f(n-1)+f(n-2)。寫到這裏,感覺很熟悉,這不就是斐波那契數列的表達式嘛?是的,就是這樣。
       但是需要注意的是,最好不要用遞歸實現,因爲會超時。。。

解答

class Solution {
public:
    int climbStairs(int n) {
    	int* way=new int[n+1]; 
    	way[0]=0;
    	way[1]=1;
    	way[2]=2;
    	int methods=0;
        if(n==0) {
        	methods=0;
        	return methods;
		}
		else if(n==1){
			methods=1;
			return methods;
		}
		else if(n==2){		
			methods=2;
			return methods;
		}
		else{
			for(int i=3;i<=n;i++){
				way[i]=way[i-1]+way[i-2];
			}
			methods=way[n];
		}
		return methods;
    }
};

       算法的時間複雜度爲O(n).







發佈了29 篇原創文章 · 獲贊 12 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章