본문 바로가기
Algorithm/백준

[백준] N과 M (2) 15650번 - java

by jackWillow 2021. 11. 6.
import java.util.Scanner;

public class Main {

	private static int N;
	private static int M;
	private static int[] arr;
	private static boolean[] visit;
	private static StringBuilder sb;
	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		N = sc.nextInt();
		M = sc.nextInt();
		arr = new int[M];
		visit = new boolean[N + 1];
		sb = new StringBuilder();
		dfs(0);
		System.out.println(sb);
	}

	private static void dfs(int depth) {
		if(depth == M) {
			sb.append(arr[0]);
			for(int i = 1; i < arr.length; i++) {
				sb.append(' ').append(arr[i]);
			}
			sb.append("\n");
			return;
		}
		int start = depth > 0 ? arr[depth - 1] + 1 : 1;
		for(int i = start; i < visit.length; i++) {
			if(!visit[i]) {
				visit[i] = true;
				arr[depth] = i;
				dfs(depth + 1);
				visit[i] = false;
			}
		}
	}
}
반응형