【问题标题】:Given an array of unique numbers, list the combination of numbers which sum equals to given integer [closed]给定一个唯一数字数组,列出总和等于给定整数的数字组合
【发布时间】:2019-01-11 10:28:10
【问题描述】:

输入

 Array =[4,2,8,11,14,6,1]
     Expectedtotal=20

输出

[2,4,6,8], [11,8,1],[6,11,1,2],[2,14,4],[14,6]

代码:

const arr = [4, 2, 8, 11, 14, 6, 1];
const target = 20;
res = _.filter(arr, v => _.filter(arr, v1 => _.filter(arr, v2 => _.filter(arr, v3 => v + v1 + v2 + v3 === target))); console.log(res);

我是 javascript 和 lodash 的初学者。我自己尝试了这段代码。请帮我写好代​​码。

【问题讨论】:

  • 到目前为止你尝试过什么?我不知道您是在测验还是询问如何获得预期的输出。请使用相关源代码编辑/更新您的帖子[您的尝试]谢谢。
  • 您使用 Stack Overflow 错误。我们不为你做你的功课。你的问题是你不知道如何从逻辑的角度来做,而不是实际的。展示您的工作并告诉我们您遇到的错误。
  • 你尝试了什么?

标签: javascript lodash


【解决方案1】:

您可以使用临时数组和索引,并通过取实际值或不取实际值来迭代下一个索引。

function subsetSum(array, sum) {

    function iter(index, temp, s) {
        if (s === sum) return result.push(temp.slice());              // exit sum found
        if (index >= array.length) return;                            // exit index over
        iter(index + 1, temp.concat(array[index]), s + array[index]); // take value
        iter(index + 1, temp, s);                                     // omit value
    }

    var result = [];
    iter(0, [], 0);
    return result;
}

console.log(subsetSum([4, 2, 8, 11, 14, 6, 1], 20).map(a => a.join(' ')));

【讨论】:

    猜你喜欢
    • 2020-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-19
    • 1970-01-01
    相关资源
    最近更新 更多