[leetcode #70] Climbing Stairs

Seongyeol Shin·2021년 10월 5일
0

leetcode

목록 보기
40/196
post-thumbnail

Problem

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?

Example 1:

Input: n = 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps

Example 2:

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 steps
3. 2 steps + 1 step

Constraints:

1 <= n <= 45

Idea

너무나 쉬운 문제다. 처음에 계단이 없을 때와 계단이 하나 있을 때 이동하는 방법의 수를 1로 정한다. 이후엔 (i-1)번째 계단에서 계단 하나를 올라가는 경우와 (i-2)번째 계단에서 계단 두 개를 올라가는 경우가 있으므로 아래와 같은 공식이 적용된다.

dp[i] = dp[i-1] + dp[i-2];

주어진 n까지 dp를 계산한 뒤 마지막에 n번째 dp 값을 리턴하면 된다.

Solution

class Solution {
    public int climbStairs(int n) {
    	int[] dp = new int[n+1];
        dp[0] = 1;
        dp[1] = 1;

        for (int i=2; i <= n; i++)
            dp[i] = dp[i-1] + dp[i-2];
   
        return dp[n];
    }
}

Reference

https://leetcode.com/problems/climbing-stairs/

profile
서버개발자 토모입니다

0개의 댓글