You are climbing a staircase. It takes n steps to reach the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Input : n = 2
Output : 2
Explanation : There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Input : n = 3
Output : 3
Explanation : There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 step
3. 2 step + 1 step
1<= n <= 45
Down-top 형식의 DP 문제이다.
1번째 계단으로 올라갈 수 있는 방법은 0번째에서 1칸만 올라오는 방법 뿐이다.
즉, steps[1] = 1
2번째 계단으로 올라갈 수 있는 방법은 0번째에서 2칸 올라오거나, 1번째 칸에서 1칸 올라오는 방법이 있다.
즉, steps[2]는 steps[0] + steps[1]이다. steps[1]은 1번째 계단까지 오는 방법의 개수이고, steps[0]은 0번째 계단까지 오는 방법의 개수이며, steps[2]로 가기 위해서 1칸을 이동할지 2칸을 이동할지만 다르기 때문에 두 개는 다른 경로이다.
따라서 steps[3] = steps[1] + steps[2] = 3이다.
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
steps = [0] * (n+1)
steps[0] = 1
steps[1] = 1
if n < 2 : return 1
for i in range(2, n+1) :
steps[i] = steps[i-2] + steps[i-1]
return steps[n]