题目
题目分析:
用动态规划解题,因为每一层楼梯都可以由i - 2层楼梯爬两层到达或者由i - 1层楼梯爬一层到达,所以转移方程为:dp[i] = dp[ i - 1] + dp[i - 2]。
代码
class Solution {
public int climbStairs(int n) {
int[] dp = new int[n];
if(n == 0) return 0;
if(n == 1) return 1;
if(n == 2) return 2;
dp[0] = 1;
dp[1] = 2;
for(int i = 2; i < n; i++){
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n - 1];
}
}
Runtime: 0 ms, faster than 100.00% of Java online submissions for Climbing Stairs.
Memory Usage: 33 MB, less than 5.26% of Java online submissions for Climbing Stairs.
Next challenges: