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

Climbing Stairs

时间:2015-06-26 06:48:28      阅读:106      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!