[PS] Leet | 322. 동전 교환

2025. 3. 28. 16:09·CS/PS

문제

You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.

Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.

You may assume that you have an infinite number of each kind of coin.

예시

Example 1:
Input: coins = [1,2,5], amount = 11
Output: 3
Explanation: 11 = 5 + 5 + 1


Example 2:

Input: coins = [2], amount = 3
Output: -1


Example 3:
Input: coins = [1], amount = 0
Output: 0

 

조건

  • 1 <= coins.length <= 12
  • 1 <= coins[i] <= 231 - 1
  • 0 <= amount <= 104

답

DP로 해결합니다.

 

각 잔액 별 최소 필요한 동전 수를 담을 리스트를 만든 뒤,

 

각 동전 종류 coin에 대해 (이전까지 잔액에서 필요했던 최소 동전 수) 와 (잔액에서 coin을 뺀 만큼에서 필요한 최소 동전 수 + 1) 중 더 작은 수를 찾습니다.

/**
 * @param {number[]} coins
 * @param {number} amount
 * @return {number}
 */
var coinChange = function(coins, amount) {
    let coinNums = [0];
    let minNum = 0;
    
    for (let i=1; i<=amount; ++i) {
        coinNums.push(amount + 1);
    }

    for (const coin of coins) {
        for (let i=coin; i<amount+1; ++i) {
            coinNums[i] = Math.min(coinNums[i], coinNums[i-coin] + 1);
        }
    }
    minNum = (coinNums[amount] !== amount + 1)? coinNums[amount] : -1;

    return minNum;
};

amount = n, coin 종류 = m 일 때

시간 복잡도 : O(nm)

공간 복잡도 : O(n)

728x90

'CS > PS' 카테고리의 다른 글

[PS] Leet | 1143. 가장 긴 공통 배열  (0) 2025.04.05
[PS] Leet | 300. 가장 긴 증가 수열  (0) 2025.04.02
[PS] Leet | 11. 가장 큰 컨테이너  (0) 2025.03.24
[PS] 같은 수의 뉴런  (0) 2025.03.21
[PS] Leet | 15. 세 개의 합  (0) 2025.03.21
'CS/PS' 카테고리의 다른 글
  • [PS] Leet | 1143. 가장 긴 공통 배열
  • [PS] Leet | 300. 가장 긴 증가 수열
  • [PS] Leet | 11. 가장 큰 컨테이너
  • [PS] 같은 수의 뉴런
Rayi
Rayi
  • Rayi
    아카이브
    Rayi
  • 전체
    오늘
    어제
    • 분류 전체보기 (262)
      • CS (40)
        • ML (3)
        • CV (2)
        • PS (34)
      • Reveiw (17)
        • Paper (17)
        • Github (0)
      • Pytorch (5)
      • Language (58)
        • Python (7)
        • JavaScript (32)
        • TypeScript (16)
        • C++ (3)
      • IDE (12)
      • Git (13)
      • Frontend (71)
        • React (8)
        • SolidJS (20)
        • CSS (12)
      • UI (3)
      • Backend (15)
        • DB (17)
        • Node.js (11)
  • 블로그 메뉴

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

  • 공지사항

  • 인기 글

  • 태그

    review
    mongo
    backend
    react
    DB
    Three
    python
    UI
    vscode
    html
    ps
    SOLID
    Express
    PRISMA
    deploy
    GAN
    CS
    C++
    CV
    nodejs
    ML
    Git
    js
    API
    postgresql
    figma
    PyTorch
    frontend
    ts
    CSS
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.5
Rayi
[PS] Leet | 322. 동전 교환
상단으로

티스토리툴바