[LeetCode] Climbing Stairs

2025. 2. 24. 17:17·공부/코딩테스트 | 알고리즘

 

문제

문제

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

풀기

해석하면 n이라는 숫자가 있는데 1 또는 2를 더해서 만들 수 있는 경우의 수 구하라는 문제이다.

대표적인 DP 문제라고 한다. (gpt 왈)

 

일단 DP로 분류되어 있던 문제이니 규칙을 찾아보려고 했었다.

n 경우 output
1 (1) 1
2 (1, 1), (2) 2
3 (2, 1), (1, 2), (1, 1, 1) 3
4 (2, 2), (2, 1, 1), (1, 2, 1), (2, 1, 1), (1, 1, 1, 1) 5
5 (2, 2, 1), (2, 1, 2), (1, 2, 2), (2, 1, 1, 1), (1, 2, 1, 1), (1, 1, 2, 1), (1, 1, 1, 2), (1, 1, 1, 1, 1) 8
... ... ...

 

n이 5일때까지 확인해보면 위 표와 같다.

output의 값을 보면 점화식은 다음과 같다는 걸 알 수 있다.

dp[n] = dp[n - 1] + dp[n - 2]

 

자 그럼 코딩 ㄱㄱ


결과

class Solution {
    fun climbStairs(n: Int): Int {
        return when (n <= 2) {
            true -> n
            false -> {
                val dp = IntArray(n + 1)

                dp[1] = 1
                dp[2] = 2

                for (i in 3 .. n) {
                    dp[i] = dp[i - 1] + dp[i - 2]
                }

                dp[n]
            }
        }
    }
}

 

 

'공부 > 코딩테스트 | 알고리즘' 카테고리의 다른 글

[LeetCode] Maximum Depth of Binary Tree  (0) 2025.02.27
[LeetCode] Min Stack  (0) 2025.02.26
[LeetCode] House Robber  (0) 2025.02.25
[LeetCode] Maximum Subarray  (0) 2025.02.24
[프로그래머스] 입양 시각 구하기(2)  (0) 2022.02.15
'공부/코딩테스트 | 알고리즘' 카테고리의 다른 글
  • [LeetCode] Min Stack
  • [LeetCode] House Robber
  • [LeetCode] Maximum Subarray
  • [프로그래머스] 입양 시각 구하기(2)
나는 유찌
나는 유찌
쩌리쨩
  • 나는 유찌
    유찌 개발 일기
    나는 유찌
  • 전체
    오늘
    어제
    • 분류 전체보기
      • 사이드 프로젝트
        • 게시판
        • 블로그(Spring boot + React.js ..
      • 데이터베이스
        • SQLD
      • 이슈 해결
      • Front
        • Javascript
        • Vue.js
        • HTML+CSS
      • Backend
        • Spring
        • ORM
        • JAVA
      • 공부
        • HTTP
        • OOP
        • 이것저것
        • 코딩테스트 | 알고리즘
      • Computer Science
        • Computer architecture
        • 데이터베이스
        • 운영체제
      • 일상
        • 독서
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    한국소설
    DIRTY READ
    access token
    jwt 로그인 구현
    Access Token Refresh Token
    히가시노 게이고
    role scope
    Spring Boot
    phantom read
    AccessDecisionVoter
    jwt
    mssql
    Spring Security AccessDecisionManager
    AntPathMatcher
    redis 분산락
    웹 개발
    spring 격리수준
    Access token 재발급
    Kotlin AccessDecisionManager
    refresh token
    spring
    Spring boot에서 JWT 구현
    추리소설
    Kotlin AntPathMatcher
    JWT이란?
    LeetCode
    독서
    mysql 격리수준
    권한 scope 처리
    pessimisticlock
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
나는 유찌
[LeetCode] Climbing Stairs
상단으로

티스토리툴바