LeetCode Climbing Stairs 遞迴求解和動態規劃法

來源:互聯網
上載者:User

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?

簡單題目,相當於fibonacci數列問題,痛點就是要會思維轉換,轉換成為遞迴求解問題,多訓練就可以了。

所以這種類型的題目相對於沒有形成遞迴邏輯思維的人來說,應該算是難題。

我的想法是:

每次有兩種選擇,兩種選擇之後又是各有兩種選擇,如此迴圈,正好是遞迴求解的問題。

寫成遞迴程式其實非常簡單,三個語句就可以:

int climbStairsRecur(int n) {if (n == 1) return 1;if (n == 2) return 2;return climbStairsRecur(n-1) + climbStairsRecur(n-2);}

但是遞迴程式一般都是太慢了,因為像Fibonacci問題一樣,重複計算了很多分支,我們使用動態規劃法填表,提高效率,程式也很簡單,如下:

int climbStairs(int n){vector<int> res(n+1);res[0] = 1;res[1] = 1;for (int i = 2; i <= n; i++){res[i] = res[i-1] + res[i-2];}return res[n];}

動態規劃法用熟了,高手就需要節省空間的了,如下:

int climbStairs2(int n){vector<int> res(3);res[0] = 1;res[1] = 1;for (int i = 2; i <= n; i++){res[i%3] = res[(i-1)%3] + res[(i-2)%3];}return res[n%3];}

當然,不使用上面的數組也是可以的,直接使用三個變數儲存結果也是一樣的。

//2014-2-10 updateint climbStairs(int n){if (n < 4) return n;int a = 2, b = 3, c = 5;for (int i = 5; i <= n; i++){a = c;c = b+c;b = a;}return c;}




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.