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?
Solution:Basic 1-d dynamic programming.
Iteration formula: a[n] = a[n-1] + a[n-2].
It means that you can either step from (n-1)th or (n-1)th stair to reach (n)th stair.
public class Solution {
public int climbStairs(int n) {
int[] A = new int[n+1];
A[0] = 1;
A[1] = 1;
for(int i = 2; i <= n; i++){
A[i] = A[i-1] + A[i-2];
}
return A[n];
}
}
No comments:
Post a Comment