๐Ÿ’ก๋ฌธ์ œ ๋ถ„์„ ์š”์•ฝ

๐Ÿ’ก์•Œ๊ณ ๋ฆฌ์ฆ˜ ์„ค๊ณ„

๐Ÿ’ก์ฝ”๋“œ

const fs = require('fs');
const path = require('path');

const input = fs.readFileSync(path.join(__dirname, 'input.txt')).toString().trim().split('\\n');

const [N, M] = input[0].split(' ').map(Number);
const numbers = Array.from(new Set(input[1].split(' ').map(Number))).sort((a, b) => a - b);

const result = [];
const visited = new Array(numbers.length).fill(false);

function backtrack(combination) {
  if (combination.length === M) {
    result.push(combination.join(' '));
    return;
  }

  for (let i = 0; i < numbers.length; i++) {
    if (visited[i]) continue; // ์ด๋ฏธ ์‚ฌ์šฉํ•œ ์ˆซ์ž๋Š” ๊ฑด๋„ˆ๋›ด๋‹ค.

    // ์ค‘๋ณต ๋ฐฉ์ง€: ํ˜„์žฌ ์ˆซ์ž๊ฐ€ ์ด์ „ ์ˆซ์ž์™€ ๊ฐ™๊ณ , ์ด์ „ ์ˆซ์ž๊ฐ€ ์‚ฌ์šฉ๋œ ๊ฒฝ์šฐ๋Š” ๊ฑด๋„ˆ๋›ด๋‹ค.
    if (i > 0 && numbers[i] === numbers[i - 1] && !visited[i - 1]) continue;

    visited[i] = true; // ์‚ฌ์šฉํ•œ ์ˆซ์ž ํ‘œ์‹œ
    backtrack([...combination, numbers[i]]);
    visited[i] = false; // ์‚ฌ์šฉํ•œ ์ˆซ์ž ๋ณต๊ตฌ
  }
}

backtrack([]);

console.log(result.join('\\n'));

๐Ÿ’ก์‹œ๊ฐ„๋ณต์žก๋„