리주의 프로그래밍 공부

[15651] N과 M (3) 본문

알고리즘 공부(백준)

[15651] N과 M (3)

Leezu_ 2021. 3. 18. 22:28

백트래킹 문제

dfs를 어느정도 이해했다고 생각했지만, 백트래킹 문제를 풀다가...

많은 사람들의 코드를 참고했다. 참고하고 혼자서 또 구현해보려다 실패하기를 반복하다, 억지로 맞췄다..

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Scanner;

public class Main {
	static int n,m;
	static int[] arr;
	static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
	public static void main(String[] args) throws IOException {
		Scanner sc = new Scanner(System.in);

		n = sc.nextInt();
		m = sc.nextInt();
        
		arr = new int[m];
		
		printResult(0);
		bw.flush();
	}
	
	public static void printResult(int cnt) throws IOException {
		if(cnt == m) {
			for(int i=0; i<m; i++) {
				bw.write(arr[i] + " ");
			}
			bw.write("\n");
			return ;
		}
		else {
			for(int i=1; i<=n; i++) {
				arr[cnt] = i;
				printResult(cnt + 1);
			}
		}
	}
}

 

'알고리즘 공부(백준)' 카테고리의 다른 글

[15652] N과 M (4)  (0) 2021.03.19
[15650] N과 M (2)  (0) 2021.03.19
[9663] N-Queen  (0) 2021.03.18
[2606] 바이러스  (0) 2021.01.13
[2293] 동전 1  (0) 2021.01.04