Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
public class Solution { public int climbStairs(int n) { // DP problem // n steps need (n-1) steps add 1 step OR (n-2) steps add 2 steps if (n <= 0) return 0; if (n == 1) return 1; if (n == 2) return 2; int[] wayTimes = new int[n+1]; wayTimes[0] = 0; wayTimes[1] = 1; wayTimes[2] = 2; for (int i = 3; i <= n; i++) wayTimes[i] = wayTimes[i-1] + wayTimes[i-2]; return wayTimes[n]; } }
No comments:
Post a Comment