Problem
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?
Example
Given an example n=3 , 1+1+1=2+1=1+2=3
return 3
Note
无需动规,无需额外空间,等同于菲波那切数列。
当然噜,也可以动规,记住dp[0] = 1
就好。
Solution
Fibonacci
public class Solution {
public int climbStairs(int n) {
if (n < 2) return 1;
int one = 1, two = 1, total = 0;
for (int i = 2; i <= n; i++) {
res = one + two;
two = one;
one = res;
}
return res;
}
}
DP
public class Solution {
public int climbStairs(int n) {
int[] dp = new int[n+1];
dp[0] = 1;
dp[1] = 1;
for (int i = 2; i <= n; i++) dp[i] = dp[i-1] + dp[i-2];
return dp[n];
}
}