提示: 给定以面额计的硬币值列表,返还金额所需的最小硬币数量是多少?如果不可能,则返回-1。
我相信我写了下面提供的可行解决方案。但是,当运行测试用例时,我的解决方案每次都会返回不同的数字!答案是正确的,或者是1。
我真的不明白为什么,因为我认为所有值都是整数,并且我对每个值都使用了“ parseInt”甚至“ round”,但仍然相差1。
const solution = (denominations, amount) => {
denominations.sort(function(a,b){
return a-b;
});
var count = 0;
var amountLeft = amount;
for(var i = denominations.length - 1; i >= 0; i--){
var curNum = denominations[i];
while(amountLeft >= curNum){
amountLeft = amountLeft - curNum;
count ++;
}
}
console.log(amountLeft);
console.log(count);
if(amountLeft > 0) return -1;
return count;
};
solution(
[2, 7, 11, 18, 14, 17, 12, 16, 9, 15, 3, 19],
4033
);