티스토리 뷰

https://www.acmicpc.net/problem/15654

 

15654번: N과 M (5)

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

www.acmicpc.net

const fs = require('fs');
const input = fs.readFileSync("./dev/stdin").toString().trim().split("\n").map(v=>v.split(' ').map(Number));
const [N,M] = input[0]
const nums = input[1].sort((a,b)=>a-b)
const answer = [];

class Node {
  constructor(item) {
    this.item = item;
    this.next = null;
  }
}

class Queue {
  constructor() {
    this.head = null;
    this.tail = null;
    this.length = 0;
  }

  push(item) {
    const node = new Node(item)
    if (this.head === null) {
      this.head = node;
    } else {
      this.tail.next = node;
    }

    this.tail = node;
    this.length += 1;
  }

  pop() {
    const popItem = this.head.item;
    this.head = this.head.next;
    this.length -= 1;
    return popItem;
  }
}

let q = new Queue();
nums.forEach(v=>{
  q.push([v])
})

while(q.length>0){
  let arr = q.pop();
  if(arr.length==M){
    answer.push(arr.join(' '))
  }else if(arr.length<M){
    nums.forEach(v=>{
      if(!arr.includes(v)){
        q.push([...arr,v])
      }
    })
  }
}
console.log(answer.join('\n'))
728x90
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함