生成器非常有用,可以提高值,也可以通过递归传递前一个和值和值:
function* sumUp(values, target, n, previous = [], sum = 0) { // Base case: if the combination of n values is target, yield it, or exit if(n <= 0) { if(sum === target) yield previous; return; } // otherwise add this combo for(const value of values) { // don't use the same number twice if(previous.includes(value)) continue; yield* sumUp(values, target, n - 1, [...previous, value], sum + value); } }
适用于:
// all combinations console.log([...sumUp([1, 2, 3, 4], 7, 2)]); // just the first console.log(sumUp([1, 2, 3, 4], 7, 2).next().value);