【问题标题】:Finding all possible combinations of numbers to reach a given sum from multible arrays从多个数组中找到所有可能的数字组合以达到给定的总和
【发布时间】:2021-01-02 06:20:53
【问题描述】:

您将如何从给定的 N、R、S 数字集合中测试所有可能的组合,以便它们相加为给定的最终数字,而您只能使用每个集合中的 1 个数字?

一个简单的例子:

要添加的数字集:

N = {1,2,3,...}
R = {4,5,6,...}
S = {7,8,9,...}

期望的结果:加起来等于 X 的所有数字,所以当 X = 12 时输出将是

[1,4,7]

【问题讨论】:

  • 对于每对 (n, r),其中 n+r 小于 X,检查 X-(n+r) 是否在 S 中。如果 S 在索引中,这应该在 O (n * n * log n).
  • @SaiBot 使用哈希,可以在O(n*n)中。

标签: algorithm search combinations subset-sum


【解决方案1】:

使用 JavaScript:

var N=[1,2,3];
var R=[4,5,6];
var S=[7,8,9];

function xInNRS(x) {
  return N.forEach(n=>R.forEach(r=>S.forEach(s=>{if(n+r+s==x) console.log([n,r,s])})));
}

console.log(12);xInNRS(12);
console.log(13);xInNRS(13);
.as-console-wrapper { max-height: 100% !important; top: 0; }

您也可以存储所有,然后测试 x,或打印 x:

var N=[1,2,3];
var R=[4,5,6];
var S=[7,8,9];

var X={};

N.forEach(n=>R.forEach(r=>S.forEach(s=>{
  var sum=n+r+s;
  if(X[sum]==undefined) X[sum]=[];
  X[sum].push([n,r,s]);
})));

console.log("All Xs");
console.log(X);

console.log("Test x");
console.log(9,X[9]!=undefined);
console.log(16,X[16]!=undefined);

console.log("Combinations for x");
console.log(9,X[9]);
console.log(12,X[12]);
console.log(13,X[13]);
.as-console-wrapper { max-height: 100% !important; top: 0; }

【讨论】:

    猜你喜欢
    • 2011-06-05
    • 2019-05-24
    • 1970-01-01
    • 1970-01-01
    • 2016-12-08
    • 2018-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多