[刷题]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?

思路:

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;
}

 

posted on 2016-04-11 17:10  wonderday  阅读(178)  评论(0编辑  收藏  举报

导航