p70

LeetCode p70 Climbing Stairs 题解

1.题目:

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?

题意:

上楼梯问题,输入楼梯层数,你每次可以上一层或者上两层。问有多少种上法。

2.解题思路:

见代码TUT我开始递归超时了。。然后仔细想,其实只要遍历一遍。每次只能上一层或者两层。
所以现在的种数就是上到前一层的种数,加上上到前两层时的种数。这样往后叠加就可以了。

3.代码


[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 
public class Solution {


public int climbStairs(int n) {

if (n == 1 || n == 2) {
return n;
}

int a = 1;
int b = 2;
int c = 0;
for (int i = 3; i <= n; i++) {
c = a + b;
a = b;
b = c;
}
return c;

}

}

4.一些总结: