组合: (不考虑顺序,无重复)
//测试用例 let dataArr = [1, 2, 3, 4, 5]; function combination(dataArr, remainNum, currentArr) { if (remainNum === 0) { console.log(...currentArr); return; } for (let i = 0; i < dataArr.length + 1 - remainNum; i++) { currentArr.push(dataArr[i]); combination(dataArr.slice(i + 1), remainNum - 1, currentArr); currentArr.pop(); } } const currentArr = []; combination(dataArr, 3, currentArr);
排列:
//测试用例 let dataArr = [1, 2, 3, 4, 5]; let num = 0; function swap(arr, m, n) { if (m === n) { return; } let temp = arr[m]; arr[m] = arr[n]; arr[n] = temp; return; } function fullPermutation(dataArr, index) { if (index === dataArr.length - 1) { console.log(...dataArr); num++; return; } for (let i = index; i < dataArr.length; i++) { swap(dataArr, index, i); fullPermutation(dataArr, index + 1); swap(dataArr, index, i); } } fullPermutation(dataArr, 0); console.log("个数:", num);
标签:index,currentArr,return,实现,arr,dataArr,js,let,排列组合 From: https://www.cnblogs.com/zcm1688/p/17470883.html