Skip to content

Commit 681171a

Browse files
week11 mission coin-change
1 parent ca9457f commit 681171a

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

โ€Žcoin-change/dev-jonghoonpark.md

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
- ๋ฌธ์ œ: https://leetcode.com/problems/coin-change/
2+
- ํ’€์ด: https://algorithm.jonghoonpark.com/2024/02/26/leetcode-322
3+
4+
## dfs๋กœ ํ’€๊ธฐ
5+
6+
```java
7+
class Solution {
8+
public int coinChange(int[] coins, int amount) {
9+
if(amount == 0) {
10+
return 0;
11+
}
12+
13+
int[] dp = new int[amount + 1];
14+
15+
List<Integer> sortedCoins = Arrays.stream(coins).boxed()
16+
.sorted(Collections.reverseOrder())
17+
.toList();
18+
19+
sortedCoins.forEach(coin -> dfs(dp, sortedCoins, amount, coin));
20+
21+
return dp[0] == 0 ? -1 : dp[0];
22+
}
23+
24+
void dfs(int[] dp, List<Integer> coins, int amount, int selectedCoin) {
25+
int currentPointer = amount - selectedCoin;
26+
if (currentPointer < 0) {
27+
return;
28+
}
29+
30+
if (dp[currentPointer] == 0 || dp[currentPointer] > dp[amount] + 1) {
31+
dp[currentPointer] = dp[amount] + 1;
32+
coins.forEach(coin -> dfs(dp, coins, currentPointer, coin));
33+
}
34+
}
35+
}
36+
```
37+
38+
### TS, SC
39+
40+
์ฝ”์ธ์˜ ์ˆ˜๋ฅผ n ์ด๋ผ๊ณ  ํ–ˆ์„ ๋•Œ, `O(n * amount ^ 2)` ์˜ ์‹œ๊ฐ„๋ณต์žก๋„์™€ `O(amount)` ์˜ ๊ณต๊ฐ„๋ณต์žก๋„๋ฅผ ๊ฐ€์ง„๋‹ค.
41+
42+
## dp๋กœ ํ’€๊ธฐ
43+
44+
```java
45+
public class Solution {
46+
public int coinChange(int[] coins, int amount) {
47+
int max = amount + 1;
48+
int[] dp = new int[amount + 1];
49+
Arrays.fill(dp, max);
50+
dp[0] = 0;
51+
52+
for (int i = 1; i <= amount; i++) {
53+
for (int j = 0; j < coins.length; j++) {
54+
if (coins[j] <= i) {
55+
dp[i] = Math.min(dp[i], dp[i - coins[j]] + 1);
56+
}
57+
}
58+
}
59+
60+
return dp[amount] > amount ? -1 : dp[amount];
61+
}
62+
}
63+
```
64+
65+
### TS, SC
66+
67+
์ฝ”์ธ์˜ ์ˆ˜๋ฅผ n ์ด๋ผ๊ณ  ํ–ˆ์„ ๋•Œ, `O(n * amount)` ์˜ ์‹œ๊ฐ„๋ณต์žก๋„์™€ `O(amount)` ์˜ ๊ณต๊ฐ„๋ณต์žก๋„๋ฅผ ๊ฐ€์ง„๋‹ค.

0 commit comments

Comments
ย (0)