Skip to content

Commit 3c9a30f

Browse files
committed
feat: coin change
1 parent f4cc680 commit 3c9a30f

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

โ€Žcoin-change/std-freejia.java

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/**
2+
* BFS ๋Š” ๋„ˆ๋น„ ์šฐ์„ ์ด๋ฏ€๋กœ, ๊ฐ€์žฅ ์–•์€ ๊นŠ์ด๋กœ ๋ชฉํ‘œ ๊ธˆ์•ก์„ ๋งŒ์กฑํ•˜๋ฉด '์ตœ์†Œ ๋™์ „ ๊ฐœ์ˆ˜'๋ฅผ ์‚ฌ์šฉํ•œ ๊ฒƒ์ž…๋‹ˆ๋‹ค.
3+
* ๋„ˆ๋น„ == ์‚ฌ์šฉํ•œ ๋™์ „ ๊ฐœ์ˆ˜
4+
*
5+
* Queue<Integer> ๋™์ „ ๊ธˆ์•ก 'ํ•ฉ' ์„ ๊ด€๋ฆฌํ•ฉ๋‹ˆ๋‹ค
6+
*
7+
* ๋ชฉํ‘œ ๊ธˆ์•ก์ด amount ์ผ ๋•Œ,
8+
* 0 ๋ถ€ํ„ฐ amount ๊นŒ์ง€์˜ ํ•ฉ์„ ์ฒดํฌํ•  boolean[] ์„ ํ™œ์šฉํ•ฉ๋‹ˆ๋‹ค.
9+
* ํ•ฉ๊ณ„ ๊ธˆ์•ก์ด '์ด๋ฏธ ๋งŒ๋“ค์–ด๋ณธ ํ•ฉ' ์ด๋ฉด boolean[] ์— ์ฒดํฌํ•˜์—ฌ ์ค‘๋ณต๋ฐฉ๋ฌธ์„ ๋ฐฉ์ง€ํ•˜๊ธฐ ์œ„ํ•จ.
10+
*
11+
*/
12+
class Solution {
13+
public int coinChange(int[] coins, int amount) {
14+
if (amount == 0) return 0; // ๋ชฉํ‘œ ๊ธˆ์•ก 0์ธ ๊ฒฝ์šฐ, '0๊ฐœ' ๋ฆฌํ„ด
15+
16+
Arrays.sort(coins); // ์ž‘์€ ๋™์ „๋ถ€ํ„ฐ ๋”ํ•ด๋ณธ๋‹ค
17+
18+
// ์ด๋ฏธ ๋งŒ๋“ค์–ด๋ณธ 'ํ•ฉ' ์€ ์ง€๋‚˜๊ฐ€๋„๋ก.
19+
boolean[] visitedAmount = new boolean[amount + 1];
20+
// ํ•ฉ
21+
Queue<Integer> amountQueue = new ArrayDeque<>();
22+
23+
amountQueue.add(0); // ์‹œ์ž‘ ๊ธˆ์•ก 0
24+
visitedAmount[0] = true;
25+
26+
int coinCount = 0; // ์‚ฌ์šฉํ•œ ๋™์ „ ๊ฐœ์ˆ˜
27+
28+
while(!amountQueue.isEmpty()) {
29+
coinCount++; // ์‚ฌ์šฉํ•œ ๋™์ „ ๊ฐœ์ˆ˜ 1๊ฐœ ์ฆ๊ฐ€
30+
31+
int queueSize = amountQueue.size();
32+
33+
for(int i = 0; i < queueSize; i++) {
34+
// ํ˜„์žฌ ๊ธˆ์•ก ํ•ฉ
35+
int currentAmount = amountQueue.poll();
36+
37+
// ๋ชจ๋“  ์ฝ”์ธ์„ ๋”ํ•ด๋ณธ๋‹ค
38+
for(int coin : coins) {
39+
// ์ฝ”์ธ์„ ๋”ํ•ด ๋ณธ ํ•ฉ.
40+
int tempAmount = currentAmount + coin;
41+
42+
if (tempAmount == amount) return coinCount; // ์ตœ์†Œ ๋™์ „ ๊ฐœ์ˆ˜ ์ฐพ์Œ
43+
44+
// ์ฒ˜์Œ ๋งŒ๋“  ํ•ฉ ์ด๊ณ , ๋ชฉํ‘œ ๊ธˆ์•ก๋ณด๋‹ค ์ ์€ ํ•ฉ์ด๋ผ๋ฉด,
45+
if (tempAmount < amount && !visitedAmount[tempAmount]) {
46+
visitedAmount[tempAmount] = true;
47+
amountQueue.add(tempAmount);
48+
}
49+
}
50+
}
51+
}
52+
return -1;
53+
}
54+
}

0 commit comments

Comments
ย (0)