查找总和等于数字的所有子数组?

use*_*513 14 javascript

您能告诉我如何找到总和等于数字的所有子数组吗?

arr[] = [2, 4, 45, 6, 0, 19]
   x  =  51
Output: [2,4,45]
Run Code Online (Sandbox Code Playgroud)

要么

arr[] = [1, 11, 100, 1, 0, 200, 3, 2, 1, 280]
    x = 280
Output: [280]
Run Code Online (Sandbox Code Playgroud)

我尝试这样,但没有得到正确的输出

arr[] = [2, 4, 45, 6, 0, 19]
   x  =  51
Output: [2,4,45]
Run Code Online (Sandbox Code Playgroud)

这个预期的输出是

console.log(getSubArray([1, 3, 6, 11, 1, 5,4],4));

output: [1,3]
     [4]
Run Code Online (Sandbox Code Playgroud)

预期输出[[1,3],[4]]是我的预期输出

Nin*_*olz 5

您可以迭代数组并采用下一个元素,或者如果在省略该元素之前未采用任何元素,则可以使用该元素。

function getSubset(array, sum) {
    function iter(temp, delta, index) {
        if (!delta) result.push(temp);
        if (index >= array.length) return;
        iter(temp.concat(array[index]), delta - array[index], index + 1);
        if (!temp.length) iter(temp, delta, index + 1);
    }

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

console.log(getSubset([2, 4, 45, 6, 0, 19], 51));                   // [2, 4, 45], [45, 6], [45, 6, 0]
console.log(getSubset([1, 11, 100, 1, 0, 200, 3, 2, 1, 280], 280)); // [280]
console.log(getSubset([1, 3, 6, 11, 1, 5, 4], 4));                  // [1, 3], [4]
Run Code Online (Sandbox Code Playgroud)