You are climbing a stair case. It takes n steps to reach to the top.code
Each time you can either climb 1 or 2 steps. In how many distinct ways
can you climb to the top?it
思路: 由於一次只能邁一個臺階或者兩個臺階, 那麼一個臺階只能由它上一個臺階或者上上一個臺階邁上來。 因此若是f(x) 表明方案數, 那麼f(x) = f(x - 1) + f(x - 2); 獲得了遞推關係。 base狀況時f(0) = 0, f(1)= 1, f(2) = 2(由於邁上第二層有兩種方案, 一種是一次邁兩步, 另外一種是一步一步的邁上去)。 io
時間複雜度:O(n)
空間複雜度:O(n)class
public class Solution { public int climbStairs(int n) { if (n <= 2) { return n; } int[] f = new int[n + 1]; f[0] = 0; f[1] = 1; f[2] = 2; for (int i = 3; i <= n; i++) { f[i] = f[i - 1] + f[i - 2]; } return f[n]; } }