題目內容
假設你正在爬樓梯。需要 n 階你才能到達樓頂。
每次你可以爬 1 或 2 個臺階。你有多少種不同的方法可以爬到樓頂呢?
注意: 給定 n 是一個正整數。
示例 1:
輸入: 2
輸出: 2
解釋: 有兩種方法可以爬到樓頂。
1. 1 階 + 1 階
2. 2 階
示例 2:
輸入: 3
輸出: 3
解釋: 有三種方法可以爬到樓頂。
1. 1 階 + 1 階 + 1 階
2. 1 階 + 2 階
3. 2 階 + 1 階
代碼實現
public class Solution {
public int ClimbStairs(int n)
{
var table = new int[n + 1];
return ClimbStairs(n, table);
}
public int ClimbStairs(int n, int[] table)
{
if (n < 0) return 0;
if (table[n] > 0) return table[n];
var result = n >= 1
? ClimbStairs(n - 1, table) + ClimbStairs(n - 2, table)
: 1;
table[n] = result;
return result;
}
}