[leetcode] Climbing Stairs

NO IMAGE

70. Climbing Stairs


You are climbing a staircase. 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?


DP入門第一題。DP實質就是cache, 把之前出現過的中間結果記錄,下次再出現相同情況的時候,通過DP table可以只用O(1)的時間複雜度得到。
dp[i]表示到達第i層樓梯的不同走法。
那麼題目中每次可以選擇走一步,或者兩步,dp[i] = dp[i-1] – dp[i-2]。
從迭代公式可以知道,base case有兩個,dp[0]和dp[1]。

public class Solution {
public int climbStairs(int n) {
if(n<=2) return n;
int[] dp = new int[n];
dp[0] = 1;
dp[1] = 2;
for(int i=2;i<n;i  ) {
dp[i] = dp[i-1]   dp[i-2];
}
return dp[n-1];
}
}