https://leetcode.com/problems/coin-change/
문제 파악
- 입력
- coins: 동전의 종류를 담은 정수 배열
- amount: 목표 금액
- 조건
- 동전은 무한히 사용할 수 있음
- 출력
- amount를 만들기 위해 필요한 최소 동전 개수 반환
- 만들 수 없으면 -1 반환
문제 풀이
BFS
class Solution {
public int coinChange(int[] coins, int amount) {
Queue<Entry> queue = new LinkedList<>();
boolean[] visited = new boolean[amount + 1];
if (amount == 0) return 0;
queue.add(new Entry(0, 0));
while (!queue.isEmpty()) {
Entry curr = queue.remove();
for (int coin : coins) {
int nextCoin = curr.amount + coin;
if (nextCoin > amount) continue;
if (nextCoin == amount) return curr.count + 1;
if (!visited[nextCoin]) {
visited[nextCoin] = true;
queue.add(new Entry(nextCoin, curr.count + 1));
}
}
}
return -1;
}
class Entry {
int amount;
int count;
Entry(int amount, int count) {
this.amount = amount;
this.count = count;
}
}
}
📊 실행 결과
'알고리즘' 카테고리의 다른 글
[LeetCode] 1091. Shortest Path in Binary Matrix (java) (0) | 2025.02.11 |
---|---|
[LeetCode] 200. Number of Islands (java) (0) | 2025.02.10 |
[LeetCode] 785. Is Graph Bipartite? (java) (0) | 2025.02.08 |
[LeetCode] 32. Longest Valid Parentheses (java) (0) | 2025.02.08 |
[LeetCode] 841. Keys and Rooms (java) (0) | 2025.02.07 |