조합
arr : [1,2,3,4] 배열
num: 3 4개 중 3개를 뽑음
function combination(arr, num) {
let result = [];
if(num == 1) return arr.map(e => [e]);
arr.forEach((e,i,array) => {
let rest = array.slice(i+1);
let combinations = combination(rest,num-1);
let combiArr = combinations.map(x => [e, ...x])
result.push(...combiArr);
})
return result;
}
순열
function combination(arr, num) {
let result = [];
if(num == 1) return arr.map(e => [e]);
arr.forEach((e,i,array) => {
let rest = [...array.slice(0,i), ...array.slice(i+1)];
let combinations = combination(rest,num-1);
let combiArr = combinations.map(x => [e, ...x])
result.push(...combiArr);
})
return result;
}
부분집합
비트연산자 활용
let arr = [1,2,3,4];
let result = [];
for(let i = 1; i < (1 << arr.length); i++) {
result.push([]);
for(let j = 0; j < arr.length; j++) {
if(i & (1 << j)) result[i-1].push(arr[j])
}
}
완전탐색
let set = new Set();
numOfCase([1,7],'')
function numOfCase(arr,str) {
if(arr.length) {
for(let i = 0; i <arr.length; i++) {
let copy = [...arr];
copy.splice(i,1);
numOfCase(copy,str + arr[i])
}
}
if(str > 0) set.add(Number(str))
}
console.log(Array.from(set))