【发布时间】:2020-12-16 07:59:55
【问题描述】:
https://leetcode.com/problems/coin-change
以下输入超时,如果 19 -> 18 或更少,则通过。
[1,2,5]
19
// e.g. n === [1, 2, 5]
// e.g. t === target sum
// c === counter, count each level
// h === hash, memo
var cc = function(n, t, c, h) {
// index
const index = t;
// if we saw before, return it
if(h[index]) {
return h[index];
}
else if(t === 0) {
// we use all the target, return the counter
return c;
}
// mi === minimum counter
let mi = Infinity;
// e.g. we loop [1, 2, 5]
for(let i=0; i<n.length; i++) {
// only allow positive
if(t-n[i] >= 0) {
// recursive
// mi === Infinity
// t-n[i], consume it
// c+1, increase the counter
// h, pass down the hash
mi = Math.min(mi, cc(n, t-n[i], c+1, h));
}
}
// Update h[index] when mi < h[index]
h[index] = mi < h[index] ? mi : h[index];
return mi;
}
var coinChange = function(n, t) {
const res = cc(n, t, 0, {});
const out = res === Infinity ? -1 : res;
return out;
};
有人知道出了什么问题吗?
标签: algorithm recursion dynamic-programming