Skip to content

Commit 3c26ea7

Browse files
committed
5. coin change
1 parent ba002c4 commit 3c26ea7

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

โ€Žcoin-change/whewchews.ts

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
function coinChange(coins: number[], amount: number): number {
2+
/* # Solution 1: BFS
3+
* ์ตœ์†Œ ๊ฒฝ๋กœ๋ฅผ ์ฐพ๋Š” ๋ฌธ์ œ => BFS
4+
* ํ˜„์žฌ๊นŒ์ง€ ์‚ฌ์šฉํ•œ ๋™์ „์˜ ๊ฐœ์ˆ˜์™€ ํ˜„์žฌ๊นŒ์ง€ ์‚ฌ์šฉํ•œ ๋™์ „์˜ ํ•ฉ์„ queue์— ๋„ฃ๋Š”๋‹ค.
5+
* visited: ์ค‘๋ณต ๋ฐฉ๋ฌธ์„ ๋ฐฉ์ง€ํ•˜๊ธฐ ์œ„ํ•œ set
6+
* ๋ˆ„์ ์•ก์ด amount์™€ ๊ฐ™์•„์ง€๋ฉด count๋ฅผ return
7+
* visited์— ๋ˆ„์ ์•ก์ด ์žˆ์œผ๋ฉด continue
8+
* coins๋ฅผ ์ˆœํšŒํ•˜๋ฉด์„œ ๋ˆ„์ ์•ก์— ๋™์ „์„ ๋”ํ•œ ๊ฐ’์ด amount๋ณด๋‹ค ์ž‘์œผ๋ฉด queue์— ๋„ฃ๋Š”๋‹ค.
9+
* queue๊ฐ€ ๋นŒ๋•Œ๊นŒ์ง€ ๋ฐ˜๋ณต
10+
* ํ๊ฐ€ ๋น„์–ด์žˆ๊ณ  amount๋ฅผ ๋งŒ๋“ค์ˆ˜ ์—†์œผ๋ฉด -1์„ return
11+
*/
12+
const queue = [[0, 0]]; // [number of coins, accumulated amount]
13+
const visited = new Set();
14+
15+
while (queue.length > 0) {
16+
const [count, total] = queue.shift();
17+
if (total === amount) {
18+
return count;
19+
}
20+
if (visited.has(total)) {
21+
continue;
22+
}
23+
visited.add(total);
24+
for (const coin of coins) {
25+
if (total + coin <= amount) {
26+
queue.push([count + 1, total + coin]);
27+
}
28+
}
29+
}
30+
return -1;
31+
// TC: ๊ฐ ๊ธˆ์•ก(amount)๋งˆ๋‹ค ๋™์ „(coins)์„ ์ˆœํšŒํ•˜๋ฏ€๋กœ O(N*M) N: amount, M: coins.length
32+
// SC: O(N) N: amount
33+
}

0 commit comments

Comments
ย (0)