Skip to content

Commit 5f4f2e5

Browse files
committed
coin change
1 parent af5c584 commit 5f4f2e5

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

coin-change/se6816.java

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
/**
2+
내림차순 정렬 후, DFS를 통한 탐색 방식
3+
coins 길이 -> N
4+
amount 값 -> M
5+
시간 복잡도 : O(N^M) -> 시간 초과
6+
공간 복잡도 : O(M)
7+
8+
*/
9+
class Solution2 {
10+
public int coinChange(int[] coins, int amount) {
11+
Arrays.sort(coins);
12+
for (int i = 0; i < coins.length / 2; i++) {
13+
int temp = coins[i];
14+
coins[i] = coins[coins.length-1-i];
15+
coins[coins.length-1-i] = temp;
16+
}
17+
return searchCoin(coins, 0, 0, amount, 0);
18+
}
19+
20+
public int searchCoin(int[] coins, int idx, int result, int target, int count) {
21+
if(result == target) {
22+
return count;
23+
}
24+
int result2 = Integer.MAX_VALUE;
25+
for(int i = idx; i < coins.length; i++) {
26+
int temp = result + coins[i];
27+
if(temp > target) {
28+
continue;
29+
}
30+
int r = searchCoin(coins, i, temp, target, count+1);
31+
if(r != -1) {
32+
result2 = Math.min(result2, r);
33+
}
34+
}
35+
36+
if(result2 == Integer.MAX_VALUE) {
37+
result2 = -1;
38+
}
39+
40+
return result2;
41+
}
42+
}
43+
44+
/**
45+
dp를 이용하여, 최저 값을 구하는 방식
46+
coins의 길이 -> N
47+
amount의 값 -> M
48+
시간 복잡도 : O(N*M)
49+
공간 복잡도 : O(M)
50+
*/
51+
class Solution {
52+
public int coinChange(int[] coins, int amount) {
53+
int[] dp = new int[amount + 1];
54+
Arrays.fill(dp, Integer.MAX_VALUE);
55+
dp[0] = 0;
56+
57+
for (int coin : coins) {
58+
for (int x = 0; x < amount; x++) {
59+
if(dp[x] == Integer.MAX_VALUE) {
60+
continue;
61+
}
62+
if((x + coin) > amount) {
63+
break;
64+
}
65+
66+
dp[x + coin] = Math.min(dp[x + coin], dp[x] + 1);
67+
68+
}
69+
}
70+
71+
return dp[amount] == Integer.MAX_VALUE ? -1 : dp[amount];
72+
}
73+
74+
}

0 commit comments

Comments
 (0)