본문 바로가기
Algorithm/백준

[백준] N과 M (3) 15651번 - java

by jackWillow 2021. 11. 6.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {

	private static int N, M;
	private static char[] arr;
	private static StringBuilder sb;
	
	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());
		N = Integer.parseInt(st.nextToken());
		M = Integer.parseInt(st.nextToken());
		arr = new char[M * 2 + 1];
		for(int i = 1; i < M * 2; i += 2) arr[i] = ' ';
		arr[M*2] = '\n';
		sb = new StringBuilder();
		dfs(0);
		System.out.println(sb);
		br.close();
	}

	private static void dfs(int depth) {
		if(depth == M) {
			sb.append(arr);
			return;
		}
		
		for(int i = 1; i < N + 1; i++) {
			arr[depth * 2] = (char)(i + '0');
			dfs(depth + 1);
		}
	}
}
반응형