首页 > 其他 > 详细

Climbing Stairs

时间:2015-06-26 06:48:00      阅读:115      评论: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?

 

This problem is actually a Fibonacci problem. The intuition to solve this problem is, the way to N steps stair is the sum of the way to N-1 and N-2 steps stairs.

  • 1, From N - 1 steps to N, there is only one way to take 1 step to get to N
  • 2, From N - 2 steps to N, there is only one way to take a 2 steps to get to N
  • 3, Also, there is no overlapping between the above 2 ways
  • 4, So, the way to get to N steps stair is the sum of N - 1 and N - 2

Code is Simple 

public int climbStairs(int n) {
if (n <= 0) return 0;
if (n == 1) return 1;
if (n == 2) return 2;
int s1 = 1;
int s2 = 2;
int result = 0;
for(int i = 2; i < n; i++){
result = s1 + s2;
s1 = s2;
s2 = result;
}
return result;
}

 

Climbing Stairs

原文:http://www.cnblogs.com/midan/p/4601374.html

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