All'alba vincerò

At dawn, I will win!

Algorithm

[백준] 15651번: N과 M

나디아 Nadia 2024. 10. 14. 19:36

✏️ 개념 공부

 

백트래킹(Backtracking)

 

3주차 개념 정리 | Notion

백트래킹(Backtracking)

thin-brisket-ae4.notion.site

 


🛠️ 문제 

15651번: N과 M

 

 

💡 풀이

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

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


const N = parseInt(input[0]);
const M = parseInt(input[1]);

const result = [];
const sequence = [];

// 백트래킹 함수
function backtrack(depth) {
  // 수열이 M개 선택되었을 때 출력
  if (depth === M) {
    result.push(sequence.join(' '));
    return;
  }

  // 1부터 N까지 수 선택 가능 (중복 허용)
  for (let i = 1; i <= N; i++) {
    sequence.push(i); // 숫자 선택
    backtrack(depth + 1); // 다음 단계로 이동
    sequence.pop(); // 선택한 숫자 제거 (백트래킹)
  }
}

backtrack(0);

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

 

 

 

Algorithm-study/Algorithm/Solving/Backtracking/15651.js at main · kwonboryong/Algorithm-study

알고리즘(algorithm) 문제 풀이 스터디 . Contribute to kwonboryong/Algorithm-study development by creating an account on GitHub.

github.com

 

3주차 - 1일 | Notion

💡문제 분석 요약

thin-brisket-ae4.notion.site