题目信息
原题链接:https://leetcode.com/problems/coin-change-ii/
原题描述
TODO:
输入输出示例
Input: amount = 5, coins = [1,2,5]
Output: 4
Input: amount = 3, coins = [2]
Output: 0
条件约束
- $$ 1 \leqslant coins.length \leqslant 300 $$
- $$ 1 \leqslant coins[i] \leqslant 5000 $$
coins
中元素不重复- $$ 0 \leqslant amount \leqslant 5000 $$
题解
分析
TODO
实现
TODO
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
33
34
35
36
| class Solution {
private Map<Integer, Map<Integer, Integer>> cacheMap;
public int change(int amount, int[] coins) {
if (amount == 0) {
return 1;
}
this.cacheMap = new HashMap<>(); // init every time
Arrays.sort(coins);
return change(amount, coins, 0);
}
public int change(int amount, int[] coins, int fromIdx) {
if (fromIdx >= coins.length || coins[fromIdx] > amount) {
return 0;
}
Map<Integer, Integer> map = cacheMap.computeIfAbsent(fromIdx, k -> new HashMap<>());
if (map.containsKey(amount)) {
return map.get(amount);
}
int count = 0;
int i = 0;
int base = 0;
while (base <= amount) {
if (base == amount) {
count += 1;
} else {
count += change(amount-base, coins, fromIdx+1);
}
base += coins[fromIdx];
}
map.put(amount, count);
return count;
}
}
|
- 时间复杂度:$$ O(n) $$
- 空间复杂度:$$ O(n) $$