【发布时间】:2018-10-15 12:17:09
【问题描述】:
我有一个数组,我想得到它的数字总和的所有组合。
let arr=[1,2,3,4,5];
1st iteration : 1+2=3,1+3=4, 1+4=5, 1+5=6
and array becomes arr[1,2,3,4,5,6]
2nd iteration : 2+1=3,2+3=5, 2+4=6, 2+5=7
and array becomes arr[1,2,3,4,5,6,7]......
and 1+2+3=6, 1+2+4=7
.
.
.
and 1+2+3+4=10
.
.
.
and 1+2+3+4+5=15
and final array becomes =[1,2,3,4,5,6,7,8,9,10,11,15]
谁能帮我为此建立一个算法?
这是我迄今为止尝试过的,我尝试准备 arr 的可能子数组的数组,但无法获得所有组合。
let arr=[1,2,3,4,5];
let a=[];
for(let i=0; i < arr.length; i++){
for(let j=0; j < arr.length; j++){
let b=[];
for( let k=i; k<=j; k++ ){
b.push(arr[k]);
}
a.push(b);
}
}
console.log(a);
【问题讨论】:
-
请添加代码,你试过了。
-
请提供您迄今为止尝试过的代码示例,以便社区可以帮助您
-
to get all combination of sums of its number.您的迭代不会执行所有组合,它们只是将第一个元素与数组的第 n 个元素相加。 -
一个 6 岁 的 StackOverflow 活跃成员必须知道,您应该提供一些代码来说明您为达到预期结果所做的尝试。
-
你是怎么得到 15 的?在那之前它似乎很简单。
标签: javascript algorithm combinations