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?

典型的斐波拉契數列,簡單的動態規劃問題,開始的時候想到f(n)=f(n-1)+f(n-2)(f(1)=1,f(2)=2)直接遞推得出答案

這樣導致非常多的冗餘計算量,簡化該模型,一直累加下去並不需要記錄先前的所有值,兩個值就夠了:

public class Solution {
    public int climbStairs(int n) {
        int c=1,a=2,b=3;
        if(n<4)return n;
        while(n>3)
        {
          c=a+b;
          a=b;
          b =c;
          n--;
        }
        return b;
    }
}


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