KimMinJun
Coding Note
KimMinJun
전체 방문자
오늘
어제
  • 분류 전체보기 (487)
    • ALGORITHM (11)
      • 정렬 (6)
      • 최단경로 (1)
      • 자료구조 (1)
      • 슬라이딩 윈도우 (1)
      • etc (2)
    • Git (5)
    • Web (24)
      • Vanilla JS (13)
      • TS (2)
      • React (7)
      • ETC (1)
    • React 공식문서 (번역, 공부) (11)
      • Quick Start (2)
      • Installation (0)
      • Describing the UI (9)
      • Adding Interactivity (0)
      • Managing State (0)
      • Escape Hatches (0)
    • Next.js 공식문서 (번역, 공부) (3)
      • Getting Started (2)
      • Building Your Application (1)
    • PS (432)
      • 백준 (187)
      • Programmers (105)
      • CodeUp (21)
      • STL (3)
      • 제코베 JS 100제 (50)
      • SWEA (0)
      • LeetCode (65)
    • IT (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록
  • 관리

공지사항

인기 글

태그

  • 그래프
  • Level 0
  • string
  • 다이나믹 프로그래밍
  • tree
  • Level1
  • 문자열
  • C++
  • Level 1
  • 제코베 JS 100제
  • recursion
  • codeup
  • 백준
  • 수학
  • programmers
  • LeetCode
  • Level 2
  • 정렬
  • js
  • C

최근 댓글

최근 글

hELLO · Designed By 정상우.
KimMinJun

Coding Note

PS/백준

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

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 해주고, 단순히 순열을 구한 후에 모두 출력해주었다.

 

 

저작자표시 (새창열림)

'PS > 백준' 카테고리의 다른 글

백준 / 그래프 / 2178번 / 미로 탐색 / JS  (0) 2023.04.28
백준 / 그래프 / 7569번 / 토마토 / JS  (1) 2023.04.28
백준 / 큐 / 1966번 / 프린터 큐 / JS  (2) 2023.03.24
백준 / 그래프 / 2606번 / 바이러스 / JS  (0) 2023.03.16
    'PS/백준' 카테고리의 다른 글
    • 백준 / 그래프 / 2178번 / 미로 탐색 / JS
    • 백준 / 그래프 / 7569번 / 토마토 / JS
    • 백준 / 큐 / 1966번 / 프린터 큐 / JS
    • 백준 / 그래프 / 2606번 / 바이러스 / JS
    KimMinJun
    KimMinJun

    티스토리툴바