Skip to content

Commit 1fc517a

Browse files
committed
coin change dp 풀이
1 parent 8862575 commit 1fc517a

File tree

1 file changed

+7
-28
lines changed

1 file changed

+7
-28
lines changed

coin-change/highball.js

Lines changed: 7 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,15 @@
11
const coinChange = function (coins, target) {
2-
if (target === 0) return 0;
2+
const dp = new Array(target + 1).fill(target + 1);
33

4-
let level = 0;
5-
let found = false;
6-
7-
let queue = [...coins];
8-
let visit = new Set(coins);
9-
10-
while (queue.length > 0) {
11-
level++;
12-
13-
const queueLength = queue.length;
14-
for (let i = 0; i < queueLength; i++) {
15-
const sum = queue.shift();
16-
17-
if (sum === target) {
18-
found = true;
19-
break;
20-
}
21-
22-
for (let j = 0; j < coins.length; j++) {
23-
if (sum + coins[j] > target || visit.has(sum + coins[j])) continue;
24-
queue.push(sum + coins[j]);
25-
visit.add(sum + coins[j]);
4+
dp[0] = 0;
5+
for (let i = 1; i <= target; i++) {
6+
for (let j = 0; j < coins.length; j++) {
7+
if (i >= coins[j]) {
8+
dp[i] = Math.min(dp[i], 1 + dp[i - coins[j]]);
269
}
2710
}
28-
29-
if (found) break;
3011
}
31-
32-
if (found) return level;
33-
else return -1;
12+
return dp[target] === target + 1 ? -1 : dp[target];
3413
};
3514

3615
console.log(coinChange([1, 2, 5], 11)); //3

0 commit comments

Comments
 (0)