假定一个数组,希望将该数组内任意元素相加,得出所有排列的结果
例子:
数组 [1,2,3]
期望得到: 1,2,3,1+2,1+3,2+3,1+2+3七种结果


1 function combinationArr(arr){ 2 var tempArr=[]; 3 if(arr.length>3){ 4 var moreArr = arr.slice(1); 5 var tempResult = combinationArr(moreArr); 6 var tempResultBak = [].concat(tempResult); 7 var copyArr=[]; 8 for(var i=0; i<tempResultBak.length; i++){ 9 copyArr.push(arr[0]+tempResultBak[i]); 10 } 11 tempArr = [arr[0]].concat(copyArr).concat(tempResult); 12 }else if(arr.length == 3){ 13 tempArr.push(arr[0]); 14 tempArr.push(arr[1]); 15 tempArr.push(arr[2]); 16 tempArr.push(arr[0]+arr[1]); 17 tempArr.push(arr[0]+arr[2]); 18 tempArr.push(arr[1]+arr[2]); 19 tempArr.push(arr[0]+arr[1]+arr[2]); 20 }else if(arr.length == 2){ 21 tempArr.push(arr[0]); 22 tempArr.push(arr[1]); 23 tempArr.push(arr[0]+arr[1]); 24 }else if(arr.length == 1){ 25 tempArr.push(arr[0]); 26 } 27 return tempArr; 28 } 29 window.onload=function(){ 30 var arr = [1,2,3,4,5,6]; 31 var result = []; 32 result = combinationArr(arr); 33 console.log(result); 34 } 35
本文介绍了一种针对数组中元素进行所有可能组合求和的算法实现,通过递归方式生成从单个元素到全部元素的所有组合结果,并计算其总和。
5万+

被折叠的 条评论
为什么被折叠?



