[코테] JS 조합 경우의 수_재귀함수

변진상·2023년 6월 17일
0

코딩테스트 준비

목록 보기
5/8
function combination(arr, N) {
  let result = [];
  if (N === 1) {
    return arr.map((ele) => [ele]);
  }

  for (let i = 0; i < arr.length - 1; i++) {
    let fixed = arr[i];
    let restArr = arr.slice(i + 1);
    let restComb = combination(restArr, N - 1);
    let atteched = restComb.map((ele) => [fixed, ...ele]);

    result.push(...atteched);
  }

  return result;
}
profile
자신을 개발하는 개발자!

0개의 댓글