项目中用到了数据组合问题,使用递归实现笛卡尔积,发现报内存溢出,给出解决办法:
1 function Descartes1(list){ 2 let resultList = []; 3 let srcLength = list.length; 4 for(let i = 1;i < srcLength; i ++){ 5 let preList = i==1 ? list[i-1]: resultList; 6 let curList = list[i]; 7 let tempPreList = [] 8 for(let j = 0; j < preList.length; j++){ 9 for(let k = 0; k < curList.length; k++){ 10 if(i == 1){ 11 tempPreList.push([preList[j],curList[k]]); 12 }else{ 13 tempPreList.push([...preList[j],curList[k]]); 14 } 15 } 16 } 17 resultList = tempPreList; 18 } 19 console.log(resultList .length) 20 return resultList; 21 }
具体思路:
使用循环每个两个数组的数据做笛卡尔积,使用递归牵涉到递归层级和数据深度问题,容易报内存溢出,改为循环可解决
标签:笛卡尔,list,curList,resultList,preList,let,tempPreList From: https://www.cnblogs.com/zxl550/p/17833175.html