Skip to content

Commit 47f3660

Browse files
committed
coin change solution
1 parent d84b261 commit 47f3660

1 file changed

Lines changed: 60 additions & 0 deletions

File tree

coin-change/hyeri0903.java

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
class Solution {
2+
int minLen = Integer.MAX_VALUE;
3+
public int coinChange(int[] coins, int amount) {
4+
/**
5+
1.문제: amount 를 만족시킬 수 있는 가장 적은 수의 coins
6+
2.조건
7+
- 모두 다른 값 integer로 구성된 배열
8+
- amount 를 만들 수 없는 경우 -1 return
9+
- coins.length 최소 1, 최대 12
10+
- 원소값 최소 = 1
11+
- amount 최소 = 0
12+
3.풀이
13+
- amount 를 만족시키는 최소 조합 길이를 구한다. dfs? -> TLE
14+
- dp
15+
*/
16+
17+
int n = coins.length;
18+
//최대 코인개수 = amount
19+
int[] dp = new int[amount + 1];
20+
Arrays.fill(dp, amount + 1);
21+
dp[0] = 0;
22+
23+
for(int i = 1; i <= amount; i++) {
24+
for(int coin : coins) {
25+
//코인 사용가능한 경우
26+
if(i - coin >= 0) {
27+
dp[i] = Math.min(dp[i], dp[i-coin] + 1);
28+
}
29+
}
30+
}
31+
//amount 못만든 경우
32+
if(dp[amount] > amount) {
33+
return -1;
34+
}
35+
return dp[amount];
36+
37+
// if(n != 0 && amount == 0) return 0;
38+
// Arrays.sort(coins);
39+
// dfs(n - 1, 0, coins, amount, 0);
40+
// if(minLen == Integer.MAX_VALUE) {
41+
// return -1;
42+
// }
43+
//return minLen;
44+
}
45+
46+
void dfs(int index, int total, int[] coins, int amount, int count) {
47+
if(total > amount) return;
48+
49+
if(total == amount) {
50+
minLen = Math.min(minLen, count);
51+
return;
52+
}
53+
54+
if(count >= minLen) return;
55+
56+
for(int i = index; i >=0; i--) {
57+
dfs(i, total + coins[i], coins, amount, count+1);
58+
}
59+
}
60+
}

0 commit comments

Comments
 (0)