数组元素任意排列算法

假定一个数组,希望将该数组内任意元素相加,得出所有排列的结果

例子:

数组      [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  
View Code

 

posted @ 2018-06-08 10:31  胡淼  阅读(180)  评论(0)    收藏  举报