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

[刷题]Climbing Stairs

时间:2016-04-11 18:21:41      阅读:131      评论: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和多少个2来组成,然后把每种组成的排列组合累加起来。

 但是这样是很容易溢出的,13的阶乘就会使int溢出。

2.递归

 最后一步只可能是1或2。是1时,相当于在前一步的所有可能情况最后各加一个1,有f(n-1)中可能;是2时,相当于在前两步的所有可能情况最后各加一个2,有f(n-2)种可能。

int climbStairs(int n) {
  if(n <= 2)
    return n;
  return climbStairs(n-2)+climbStairs(n-1);
}

  然后,这不就是斐波拉切数列吗……你是不是想起了什么?把递归变为循环。

int climbStairs(int n) {
  if(n <= 2)
    return n;
  int last1 = 2;
  int last2 = 1;
  int ret;
  for(int i = 3; i<= n; i++){
    ret = last1 + last2;
       last2 = last1;
       last1 = ret;
   }
   return ret;
}

 

[刷题]Climbing Stairs

标签:

原文地址:http://www.cnblogs.com/wonderday/p/5379150.html

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