PS/백준

백준 / 백트래킹 / 15654번 / N과 M (5) / JS

KimMinJun 2023. 4. 1. 00:33

< 문제 바로가기 >

 

15654번: N과 M (5)

N개의 자연수와 자연수 M이 주어졌을 때, 아래 조건을 만족하는 길이가 M인 수열을 모두 구하는 프로그램을 작성하시오. N개의 자연수는 모두 다른 수이다. N개의 자연수 중에서 M개를 고른 수열

www.acmicpc.net

 

/* N과 M (5) */
const fs = require('fs');
// const filePath = process.platform === 'linux' ? '/dev/stdin' : '../input.txt';
const filePath = process.platform === 'linux' ? '/dev/stdin' : 'BOJ/input.txt';
const input = fs.readFileSync(filePath).toString().trim().split('\n');

const [N, M] = input.shift().split(' ').map(Number);
const N_LIST = input.shift().split(' ').map(Number);

function solution(N, M, N_LIST) {
  const getPermutation = (N_LIST, M) => {
    let result = [];

    if (M === 1) return N_LIST.map((el) => [el]);

    N_LIST.forEach((fixed, idx) => {
      let rest = [...N_LIST.slice(0, idx), ...N_LIST.slice(idx + 1)];
      let combinationList = getPermutation(rest, M - 1);
      let attached = combinationList.map((el) => [fixed, ...el]);

      result.push(...attached);
    });

    return result;
  };

  const SORTED_N_LIST = [...N_LIST].sort((a, b) => a - b);
  
  let result = getPermutation(SORTED_N_LIST, M);
  result.forEach((el) => {
    console.log(el.join(' '));
  });
}

solution(N, M, N_LIST);

input으로 들어오는 배열을 sorting 해주고, 단순히 순열을 구한 후에 모두 출력해주었다.