題目:
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?
Note: Given n will be a positive integer.
Example 1:
Input: 2 Output: 2 Explanation: There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps
Example 2:
Input: 3 Output: 3 Explanation: There are three ways to climb to the top. 1. 1 step + 1 step + 1 step 2. 1 step + 2 steps 3. 2 steps + 1 step
當n=1時,有一種路徑;當n=2時,有兩種路徑;當n=3時,有三種路徑。當n=4時,有五種,n=5時有八種。可見,n的當前項等於前兩項相加之和。應該把每項的值存放在list集合中,首先先對list集合的數值進行初始化,對第一項和第二項賦值爲1,從第三項開始的每一項都等於前兩項相加之和。最後,返回list集合中的最後一項。
代碼:
class Solution(object):
def climbStairs(self,n):
con = [0]*(n+1)
con[0] = 1
con[1] = 1
i = 2
while i<= n:
con[i] = con[i-2]+con[i-1]
i = i+1
return con[-1]