[LeetCode][322. Coin Change] 3 Approaches: DFS, BFS, Dynamic Programming
By Long Luo
This article is the solution 3 Approaches: DFS, BFS, DP of Problem 322. Coin Change.
Here shows 3 Approaches to slove this problem: DFS, BFS and Dynamic Programming.
DFS
TLE!1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30class Solution {
int minCount = Integer.MAX_VALUE;
public int coinChange(int[] coins, int amount) {
if (amount <= 0) {
return 0;
}
minCount = Integer.MAX_VALUE;
dfs(coins, amount, 0);
return minCount == Integer.MAX_VALUE ? -1 : minCount;
}
private int dfs(int[] coins, int remain, int count) {
if (remain < 0) {
return -1;
}
if (remain == 0) {
minCount = Math.min(minCount, count);
return count;
}
for (int x : coins) {
dfs(coins, remain - x, count + 1);
}
return -1;
}
}
Sorting the array first, then use DFS:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25class Solution {
int minAns = Integer.MAX_VALUE;
public int coinChange(int[] coins, int amount) {
Arrays.sort(coins);
minAns = Integer.MAX_VALUE;
coinChange(coins, amount, coins.length - 1, 0);
return minAns == Integer.MAX_VALUE ? -1 : minAns;
}
private void coinChange(int[] coins, int amount, int index, int cnt) {
if (amount == 0) {
minAns = Math.min(minAns, cnt);
return;
}
if (index < 0) {
return;
}
for (int k = amount / coins[index]; k >= 0 && k + cnt < minAns; k--) {
coinChange(coins, amount - k * coins[index], index - 1, cnt + k);
}
}
}
Memory DFS:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33public class Solution {
public int coinChange(int[] coins, int amount) {
if (amount <= 0) {
return 0;
}
return coinChange(coins, amount, new int[amount]);
}
private int coinChange(int[] coins, int rem, int[] count) {
if (rem < 0) {
return -1;
}
if (rem == 0) {
return 0;
}
if (count[rem - 1] != 0) {
return count[rem - 1];
}
int min = Integer.MAX_VALUE;
for (int coin : coins) {
int res = coinChange(coins, rem - coin, count);
if (res >= 0 && res < min) {
min = 1 + res;
}
}
count[rem - 1] = (min == Integer.MAX_VALUE) ? -1 : min;
return count[rem - 1];
}
}
Analysis
- Time Complexity: \(O(amount \times n)\)
- Space Complexity: \(O(amount)\)