标签:
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?
https://leetcode.com/problems/climbing-stairs/
直接递归超时了,要动态规划。
打印前几个数就可以看出规律,1, 2, 3, 5, 8...
从3开始dp[i] = dp[i - 1] + dp[i - 2]。
1 /** 2 * @param {number} n 3 * @return {number} 4 */ 5 var climbStairs = function(n) { 6 if(n === 0) return 0; 7 if(n === 1) return 1; 8 if(n === 2) return 2; 9 var dp = [0, 1, 2]; 10 for(var i = 3; i <= n; i++) 11 dp[i] = dp[i - 1] + dp[i - 2]; 12 return dp[n]; 13 };
[LeetCode][JavaScript]Climbing Stairs
标签:
原文地址:http://www.cnblogs.com/Liok3187/p/5229318.html