问题描述:
You are climbing a staircase. It takes n steps to reach the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
思路:
设num(i) 是登i级台阶的所有方法数
则num(i) = num(i-1) + num(i-2)
Base Case: num[0]=0; num[1]=1; num[2]=2
非常简单,代码一遍通过:
class Solution {
public int climbStairs(int n) {
int[] num = new int[n+1]; //from 0 to n
num[0] = 1;
num[1] = 1;
for (int i=2; i<=n; i++){
num[i] = num[i-1] + num[i-2];
}
return num[n];
}
}
时间复杂度:O(n)