码迷,mamicode.com
首页 > 其他好文 > 详细

Climbing Stairs <LeetCode>

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

标签:style   blog   color   io   ar   div   问题   代码   log   

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>

标签:style   blog   color   io   ar   div   问题   代码   log   

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

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