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?
Note: Given n will be a positive integer.
Example 1:
Input: 2 Output: 2 Explanation: There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 stepsExample 2:
Input: 3 Output: 3 Explanation: There are three ways to climb to the top. 1. 1 step + 1 step + 1 step 2. 1 step + 2 steps 3. 2 steps + 1 step
爬楼梯。题意是给一个数字n代表楼梯的高度,你可以每次爬一步或者两步,求有多少种不同的爬法。
这道题有两种解法,一种是数学解法,一种是动态规划。
首先是数学解法,这个题本质上是斐波那契数列。当输入为1, 2, 3, 4, 5, 6, 7, 8, 9, 10时,观察输出为1, 2, 3, 5, 8, 13, 21, 34, 55, 89。所以做法就很直观了。
迭代
时间O(n)
空间O(n)
1 /** 2 * @param {number} n 3 * @return {number} 4 */ 5 var climbStairs = function (n) { 6 const climing = []; 7 // using variables because they allocate a memory only once 8 let minusTwoSteps = 1; 9 if (n === 1) { 10 return 1; 11 } 12 let minusOneStep = 2; 13 if (n === 2) { 14 return 2; 15 } 16 let current = 0; 17 for (let i = 3; i <= n; i++) { 18 current = minusTwoSteps + minusOneStep; // current step - is a sum of two previous ones 19 minusTwoSteps = minusOneStep; // -2 steps for next iteration would be current - first 20 minusOneStep = current; // -1 step for next iteration would be our current 21 } 22 return current; 23 };
DP
dp[i]数组的定义是跑到第i层楼的时候,上楼梯的组合数是多少。几个初始值是dp[0] = 0, dp[1] = 1, dp[2] = 2。因为每次既可以爬一层楼,也可以爬两层楼,所以当你需要知道第i层楼的爬法的时候,你需要看的是我爬到i - 2层楼有几种爬法和我爬到i - 1层楼有几种爬法。所以状态转移方程就是dp[i] = dp[i - 1] + dp[i - 2]。
时间O(n)
空间O(n)
JavaScript实现
1 /** 2 * @param {number} n 3 * @return {number} 4 */ 5 var climbStairs = function (n) { 6 if (n === 0) return 0; 7 let dp = [n + 1]; 8 dp[0] = 1; 9 dp[1] = 1; 10 for (let i = 2; i <= n; i++) { 11 dp[i] = dp[i - 1] + dp[i - 2]; 12 } 13 return dp[n]; 14 };
Java实现
1 class Solution { 2 public int climbStairs(int n) { 3 if (n == 0) return 0; 4 int[] dp = new int[n + 1]; 5 dp[0] = 1; 6 dp[1] = 1; 7 for (int i = 2; i <= n; i++) { 8 dp[i] = dp[i - 1] + dp[i - 2]; 9 } 10 return dp[n]; 11 } 12 }
相关题目