LeetCode 70 Climbing Stairs

Problem:數組

You are climbing a stair case. It takes n steps to reach to the top.spa

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?.net

Summary:code

n級樓梯,每次上1或2階,求共有多少種不一樣的上法。blog

Analysis:遞歸

這道題實際上爲斐波那契數列,有如下幾種解法。get

1. 遞歸it

首先想到的是遞歸寫法,一次上1階和2階是兩種不一樣方法,因此上n級樓梯:io

  1. 若最後一步上了1階,則共有climbStairs(n - 1)種方法。
  2. 若最後一步上了2階,則共有climbStairs(n - 2)種方法。

對於每一步,都有以上兩種不一樣考慮。class

但遞歸寫法效率過低,TLE。。

1 class Solution {
2 public:
3     int climbStairs(int n) {
4         if (n == 1) return 1;
5         if (n == 2) return 2;
6         return climbStairs(n - 2) + climbStairs(n - 1);
7     }
8 };

2. 思路同上一種方法,改用了動態規劃,節省了時間。

 1 class Solution {
 2 public:
 3     int climbStairs(int n) {
 4         int *steps = new int[n + 1];
 5         steps[0] = 1; steps[1] = 1; steps[2] = 2;
 6         
 7         for (int i = 3; i < n + 1; i++) {
 8             steps[i] = steps[i - 1] + steps[i - 2];
 9         }
10         
11         return steps[n];
12     }
13 };

 3. 下面兩種方法參考 http://blog.csdn.net/kenden23/article/details/17377869 在動態規劃的基礎上節省空間。

 1 class Solution {
 2 public:
 3     int climbStairs(int n) {
 4         int steps[3];
 5         steps[0] = 1; steps[1] = 1;
 6         
 7         for (int i = 2; i < n + 1; i++) {
 8             steps[i % 3] = steps[(i - 1) % 3] + steps[(i - 2) % 3];
 9         }
10         
11         return steps[n % 3];
12     }
13 };

或者不開數組,直接用三個變量解決問題

 1 class Solution {
 2 public:
 3     int climbStairs(int n) {
 4         if (n <= 2) return n;
 5         int a = 1, b = 1, c = 2;
 6         
 7         for (int i = 3; i < n + 1; i++) {
 8             a = b;
 9             b = c;
10             c = a + b;
11         }
12         
13         return c;
14     }
15 };
相關文章
相關標籤/搜索