码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode][JavaScript]Climbing Stairs

时间:2016-03-01 00:50:44      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:

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?

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!