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?
题意:爬台阶问题。每次能爬一个或两个台阶,问一个有n个台阶的话,一共有几种方法爬到顶端。
思路:
n<=1,此时只有一种。
n>1时,对于每一个台阶i,要到达台阶,最后一步都有两种方法,从i-1迈一步,或从i-2迈两步。
也就是说到达台阶i的方法数=达台阶i-1的方法数+达台阶i-2的方法数。所以该问题是个DP问题。
d(0) = 1
d(1) = 1
d(2) = d(2-1) + d(2-2)
d(3) = d(3-1) + d(3-2)
……
好吧,状态转移方程其实就是Fibonacci数列。
代码实现给出两种方案吧:
python代码如下:
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if n<=1:
return 1
res = []
res.append(1)
res.append(1)
for i in range(2,n+1):
res.append(res[-1]+res[-2])
return res[-1]
Java代码如下:
public class Solution {
public int climbStairs(int n) {
if (n<=1)
return 1;
int oneStep=1,twoStep = 1,res = 0;
for (int i = 2; i <= n; i++) {
res = oneStep + twoStep;
twoStep = oneStep;
oneStep = res;
}
return res;
}
}