我想解决零钱的问题.我使用了两段类似的代码,但结果是一段通过,而另一段运行超时.我想知道为什么这两段类似的代码有两个不同的结果,请解释一下原理.
这个问题的leetcode链接: https://leetcode.cn/problems/coin-change/description/
超过时限的输入是:
币= [186 419,83,408]
金额= 6249
1.通过一:
var coinChange = function(coins, amount) {
const filter = amount + 1;
const memo = new Array(amount + 1).fill(filter);
const dp = function(coins, amount) {
if (amount === 0) {
return 0;
}
if (amount < 0) {
return -1;
}
if (memo[amount] !== filter) {
return memo[amount];
}
let res = Infinity;
for (let coin of coins) {
let subAmount = dp(coins, amount - coin);
if (subAmount === -1) {
continue;
}
res = Math.min(res, subAmount + 1);
}
memo[amount] = (res === Infinity) ? -1 : res;
return memo[amount];
}
return dp(coins, amount);
}
- 一次运行超时:
var coinChange = function(coins, amount) {
const filter = amount + 1;
const memo = new Array(amount + 1).fill(filter);
const dp = function(amount) {
if (amount === 0) {
return 0;
}
if (amount < 0) {
return -1;
}
if (memo[amount] !== filter) {
return memo[amount];
}
for (let coin of coins) {
let subAmount = dp(amount - coin);
if (subAmount === -1) {
continue;
}
memo[amount] = Math.min(memo[amount], subAmount + 1);
}
return memo[amount] === filter ? -1 : memo[amount]
}
return dp(amount);
}