1、排列組合(子串不重復)-組成字符串
function combination(arr, index = 0, group = []) { let temporaryArr = []; temporaryArr.push(arr[index]); for (let i = 0; i < group.length; i++) { temporaryArr.push(group[i] + arr[index]); } group = group.concat(temporaryArr) if (index + 1 >= arr.length) { return group; } return combination(arr, index + 1, group); } console.log(combination(['a', 'b', 'c', 'd']));
結果
2、排列組合(單個子串不重復)-組成數組
// 排列組合(子串不重復)-組成數組 function combination2(arr, index = 0, group = []) { let temporaryArr = []; temporaryArr.push([arr[index]]); for (let i = 0; i < group.length; i++) { if (Array.isArray(group[i])) { temporaryArr.push([...group[i], arr[index]]) } else { temporaryArr.push([group[i], arr[index]]) } } group = group.concat(temporaryArr) if (index + 1 >= arr.length) { return group; } return combination2(arr, index + 1, group); } console.log(combination2(['a', 'b', 'c', 'd']));
3、全排列組合,每個組合所有元素都參與
// 全排列組合,每個組合所有元素都參與 function combination3(arr) { let res = [] function fn(temporaryArr, leftArr) { if (temporaryArr.length === arr.length) { res.push(temporaryArr) } else { for (let i = 0; i < leftArr.length; i++) { let temp = [...leftArr] temp.splice(i, 1) // 循環每次將當前這個 與 除了當前這個進行遞歸組合 fn(temporaryArr.concat(leftArr[i]), temp) } } } fn([], arr) return res } console.log(combination3(['a', 'b', 'c', 'd']))
4、一對多,單向全組合
// 單向全組合 function combination4(arr){ let lengthArr = []; let productArr = []; let result = []; let length = 1; for(let i = 0; i < arr.length; i++){ let len = arr[i].length; lengthArr.push(len); productArr.push(i === 0 ? 1 : arr[i - 1].length * productArr[i - 1]); length *= len; } for(let i = 0; i < length; i++){ let resultItem = []; for(let j = 0; j < arr.length ; j ++){ resultItem.push(arr[j][Math.floor(i / productArr[j]) % lengthArr[j]]); } result.push(resultItem); } return result } console.log(combination4([['a','b','c'],['1','2','3'],['X','Y']]));




