Skip to content

Commit 35ded94

Browse files
committed
Coin Change Solution
1 parent acaecff commit 35ded94

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

coin-change/naringst.js

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/**
2+
* @param {number[]} coins
3+
* @param {number} amount
4+
* @return {number}
5+
*/
6+
7+
/**
8+
* combination sum 풀이를 활용했지만 amount가 커서
9+
* time limit exceeded
10+
* */
11+
12+
var coinChange = function (coins, amount) {
13+
let answer = [];
14+
let coins_desc = coins.reverse();
15+
16+
if (amount === 0) return 0;
17+
18+
function permute(arr = [], sum = 0, index = 0) {
19+
if (sum > amount) return;
20+
// 같은 경우에만 result에 담기
21+
if (sum === amount) {
22+
if (answer.length === 0) {
23+
answer = [...arr];
24+
} else {
25+
if (arr.length < answer.length) {
26+
answer = [...arr];
27+
} else {
28+
return answer.length;
29+
}
30+
}
31+
}
32+
for (let i = index; i < coins.length; i++) {
33+
// target보다 합이 작으면 재귀적으로 해당 값을 arr에 넣고, sum에 추가
34+
permute([...arr, coins_desc[i]], sum + coins_desc[i], i);
35+
}
36+
}
37+
permute();
38+
return answer.length === 0 ? -1 : answer.length;
39+
};
40+
41+
/**
42+
* 풀이(참고): combination sum을 dp로 풀려고 했었는데, 사실 이 문제가 dp로 풀어야 하는 문제
43+
*/
44+
45+
/**
46+
* @param {number[]} coins
47+
* @param {number} amount
48+
* @return {number}
49+
*/
50+
var coinChange = function (coins, amount) {
51+
let dp = Array.from({ length: amount + 1 }, () => Infinity);
52+
dp[0] = 0;
53+
54+
for (const coin of coins) {
55+
for (let i = coin; i <= amount; i += 1) {
56+
dp[i] = Math.min(dp[i], dp[i - coin] + 1);
57+
}
58+
}
59+
60+
return dp[amount] === Infinity ? -1 : dp[amount];
61+
};

0 commit comments

Comments
 (0)