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代码如下:
1 class Solution(object):
2 def climbStairs(self, n):
3 """
4 :type n: int
5 :rtype: int
6 """
7 if n<=1:
8 return 1
9 res = []
10 res.append(1)
11 res.append(1)
12 for i in range(2,n+1):
13 res.append(res[-1]+res[-2])
14 return res[-1]
Java代码如下:
1 public class Solution {
2 public int climbStairs(int n) {
3 if (n<=1)
4 return 1;
5
6 int oneStep=1,twoStep = 1,res = 0;
7
8 for (int i = 2; i <= n; i++) {
9 res = oneStep + twoStep;
10 twoStep = oneStep;
11 oneStep = res;
12 }
13
14 return res;
15 }
16 }