-
Notifications
You must be signed in to change notification settings - Fork 0
/
322.零钱兑换.js
67 lines (56 loc) · 1.31 KB
/
322.零钱兑换.js
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
* @lc app=leetcode.cn id=322 lang=javascript
*
* [322] 零钱兑换
*/
// @lc code=start
/**
* @param {number[]} coins
* @param {number} amount
* @return {number}
*/
/*
解法 1 BFS
解法 2 动态规划
// dp[n] 表示当 总金额数为 n 时的所有组合的最少情况
// dp[n] = n >= k ? Math.min(dp[i], dp[n-k]+1) k = 1,2,5
*/
// var coinChange = function(coins, amount) {
// let max = amount + 1;
// let dp = new Array(amount + 1).fill(max);
// dp[0] = 0;
// for (let i = 1; i < max; i++) {
// for (let j = 0; j < coins.length; j++) {
// if (i - coins[j] >= 0) {
// dp[i] = Math.min(dp[i], dp[i - coins[j]] + 1);
// }
// }
// }
// return dp[amount] === max ? -1 : dp[amount];
// };
// BFS
var coinChange = function(coins, amount) {
let q = [amount],
count = 0,
visited = new Set();
coins.sort((a, b) => b - a); // 从大到小排列
while (q.length !== 0) {
let size = q.length;
for (let k = 0; k < size; k++) {
let value = q.shift();
if (value === 0) {
return count;
}
for (let i = 0; i < coins.length; i++) {
let res = value - coins[i];
if (res >= 0 && !visited.has(res)) {
visited.add(res);
q.push(res);
}
}
}
count++;
}
return -1;
};
// @lc code=end