Skip to content

Commit a5bcbc9

Browse files
committed
solve: coin change
1 parent f484092 commit a5bcbc9

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

β€Žcoin-change/JustHm.swift

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// time: O(n*amount) space: O(amount)
2+
class Solution {
3+
func coinChange(_ coins: [Int], _ amount: Int) -> Int {
4+
var queue: [(count: Int, total: Int)] = [(0, 0)] // (동전 개수, λˆ„μ  κΈˆμ•‘)
5+
var visited = Set<Int>() // 쀑볡 제거용
6+
var index = 0 // 큐의 head
7+
8+
while index < queue.count {
9+
let (count, total) = queue[index]
10+
index += 1
11+
12+
if total == amount {
13+
return count
14+
}
15+
if visited.contains(total) {
16+
continue
17+
}
18+
visited.insert(total)
19+
// BFS 방식
20+
for coin in coins { // λͺ¨λ“  코인을 ν˜„μž¬ λˆ„μ κΈˆμ•‘μ— ν•œ λ²ˆμ”© λ”ν•΄μ„œ 큐에 μ €μž₯
21+
let newTotal = total + coin
22+
if newTotal <= amount {
23+
queue.append((count + 1, newTotal))
24+
}
25+
}
26+
}
27+
return -1
28+
}
29+
}

0 commit comments

Comments
Β (0)