-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0322-coin-change.java
More file actions
34 lines (33 loc) · 1016 Bytes
/
0322-coin-change.java
File metadata and controls
34 lines (33 loc) · 1016 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {
public int coinChange(int[] coins, int amount) {
if (amount == 0) return 0;
Queue<Integer> q = new LinkedList<>();
for (int c: coins) {
if (c > amount) continue;
q.offer(c);
}
boolean[] visited = new boolean[amount + 1];
int steps = 1;
while (!q.isEmpty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
int num = q.poll();
if (num == amount) {
return steps;
}
if (num > amount || visited[num]) {
continue;
}
visited[num] = true;
for (int c: coins) {
if (c > amount) continue;
if (c + num <= amount && !visited[c + num]) {
q.offer(c + num);
}
}
}
steps++;
}
return -1;
}
}