命题:从成员数为N的集合S中,选出M个元素,分别求其排列与组合结果集,即 A(N, M)与C(N, M)
js解法:
1 var allResult = []; 2 3 function queue(arr, size, result){ 4 //first call 5 if(result == undefined){ 6 result = []; 7 if(size > arr.length){ 8 return; 9 } 10 } 11 12 if(result.length == size){ 13 store(result); 14 } 15 16 for(var i =0 ;i < arr.length; i++){ 17 var newArr = [].concat(arr), 18 curItem = newArr.splice(i,1); 19 arguments.callee(newArr, size, [].concat(result,curItem)); 20 } 21 } 22 23 24 function choose(arr, size, result ){ 25 //first call 26 if(result == undefined){ 27 result = []; 28 console.log(‘choose ‘+ size + ‘ items from: ‘ + arr); 29 } 30 if(size > arr.length){ 31 return; 32 } 33 34 if(size == arr.length){ 35 store([].concat(result, arr)); 36 }else{ 37 for(var i =0 ; i < arr.length; i++){ 38 var newResult = [].concat(result); 39 newResult.push(arr[i]); 40 41 if(size == 1){ 42 store(newResult); 43 }else{ 44 var newArr = [].concat(arr); 45 newArr.splice(0, i + 1); 46 arguments.callee(newArr, size - 1, newResult); 47 } 48 } 49 } 50 } 51 52 function store(result){ 53 console.log(result); 54 allResult.push(result); 55 } 56 57 58 var arr = [‘姬光‘,‘王子‘, ‘三桂‘,‘科长‘,‘猫哥‘]; 59 60 choose(arr, 4); 61 //queue(arr, arr.length); 62 63 console.log(‘The number of result sets: ‘ + allResult.length);
个人原创,如有漏洞或建议,请留言。