您的位置:首页 > 大数据 > 人工智能

LeetCode - Climbing Stairs

2014-01-15 10:41 204 查看
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?

http://oj.leetcode.com/problems/climbing-stairs/

Solution:

Simple dp. We know that if there is one stair, we have one way, if there are two stairs, we have two ways.

So assume we have step
ways for n stairs, and for n+1 stairs, step[n+1] = step
+ step[n-1]. We can use step
+ 1 or step[n-1] + 2.

Does this formula seem similar? Sure it is Fibonacci number!!!

So I just provide the iterative way for this problem. 

https://github.com/starcroce/leetcode/blob/master/climbing_stairs.cpp

//8 ms for 45 test cases
class Solution {
public:
int climbStairs(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int a = 1, b = 2;
if(n == 1) {
return a;
}
if(n == 2) {
return b;
}
int c;
for(int i = 3; i <= n; i++) {
c = a + b;
a = b;
b = c;
}
return c;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode dp