首页 > 其他 > 详细

Climbing Stairs <LeetCode>

时间:2014-08-31 14:22:31      阅读:178      评论:0      收藏:0      [点我收藏+]

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?

 

1:下面用的是递归的方法,但是会超时

 

 1 class Solution {
 2 public:
 3     int total_steps=0;
 4     int climbStairs(int n) {
 5         if(n==0)
 6         {
 7             total_steps++;
 8         }
 9         else
10         {
11             if(n>=1)
12             {
13                climbStairs(n-1);
14             }
15             if(n>=2)
16             {
17                climbStairs(n-2);
18             }
19         }
20         return total_steps;
21     }
22 };

 

 

2:用动态规划,解决了问题,代码如下:

 

 1 class Solution {
 2 public:
 3     int total_steps=0;
 4     int climbStairs(int n) {
 5     if(n==1)   return 1;
 6     if(n==2)   return 2;
 7     int solutions[1000];
 8     solutions[0]=0;
 9     solutions[1]=1;
10     solutions[2]=2;
11     int i=3;
12     while(i<=n)
13     {
14         solutions[i]=solutions[i-1]+solutions[i-2];
15         i++;
16     }
17     return solutions[n];
18     }
19 };

 

Climbing Stairs <LeetCode>

原文:http://www.cnblogs.com/sqxw/p/3947581.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!