javascript - 算法:每组数字加起来等于某个数字

标签 javascript algorithm

我很难理解这个问题。给定一组数字 ([1, 2, 3, 4, 5, 6, 7,8, 9, 10, 11, 12]) 我想找到所有可能的组合12 岁。

因此,[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] 等于 [1, 2, 9 ][12] 一样。

理想情况下,返回值类似于...

[
  [1,1,1,1,1,1,1,1,1,1,1,1],
  [1,1,1,1,1,1,1,1,1,1,2],
  …
]

我不一定需要解决编程问题,只需要算法或算法中的方向。

这是我目前所拥有的:

var subsets = function (arr, total, answers, itteration) {
    var answers = answers || [[0]],
        itteration = itteration || 0,
        thisTest = answers[itteration],
        testTotal = sum(thisTest, total);

    if (testTotal === total) {
        if (arr.length === itteration) {
            return answers;
        }

        return subsets(arr, total, answers, itteration++);
    }

    for (var i=0, i<arr.length; i++) {
        thisTest.push(arr[i]);

        if (sum(thisTest, total) === total) {

        }
    }
}

var sum = (array, total) {
    var tempTotal = 0;

    return array.forEach(function (el) {
        return tempTotal += el;
    });
}


console.log(subsets([1,2,3,4,5,6,7,8,9,10,11,12], 12));

最佳答案

关于javascript - 算法:每组数字加起来等于某个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29763175/

相关文章:

javascript - Vue 组合事件处理程序

javascript - 如何为对象的所有实例调用对象函数

javascript - 使用Angularjs定期刷新html表格数据

java - 找出两百万以下所有素数的总和。我的程序不适用于非常大的数字

c++ - 如何在C++中基于第3列(索引除以3)快速排序一维数组

algorithm - 二进制串余数 3

algorithm - k近邻算法应该使用数字0-9的二值图像的哪些特征?

python - 等效 Unicode 字符串的相等性

javascript - Ionic v3 将值传递给另一个页面

javascript - 在不打开控制台的情况下在 Firefox 中显示 Javascript 错误计数