原题网址:https://leetcode.com/problems/climbing-stairs/
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?
方法一:动态规划。
public class Solution {
public int climbStairs(int n) {
int[] ways = new int[n+1];
ways[0] = 1;
for(int i=0; i<n; i++) {
if (i+1 <= n) ways[i+1] += ways[i];
if (i+2 <= n) ways[i+2] += ways[i];
}
return ways[n];
}
}
方法二:动态规划,优化空间。
public class Solution {
public int climbStairs(int n) {
if (n<2) return 1;
int previous = 1;
int current = 1;
for(int i=2; i<=n; i++) {
int next = previous + current;
previous = current;
current = next;
}
return current;
}
}