[アルゴリズム]標準-1565 1(NとM(6)/Java

12953 ワード

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;


public class Main {
	
	private static int N, M;
	private static int[] map;
	private static int[] result;
	private static boolean[] visit;
	private static StringBuilder sb = new StringBuilder();
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());
		
		
		N = Integer.parseInt(st.nextToken());
		M = Integer.parseInt(st.nextToken());
		
		map = new int[N];
		result = new int[M];
		visit = new boolean[N+1];
		
		st = new StringTokenizer(br.readLine());
		
		for (int i=0; i<N; i++) {
			map[i] = Integer.parseInt(st.nextToken());
		}
		
		Arrays.sort(map);
		dfs(0, 0);
		System.out.print(sb);
		
	}

	private static void dfs(int start , int at ) {
		//종료 조건
		if (start == M) {
			for (int i=0; i<result.length; i++) {
				sb.append(result[i]).append(" ");
			}
			sb.append("\n");
		} else {
			
			for (int i= at; i<N; i++) {
				if (!visit[i]) {
					visit[i] = true;
					result[start] = map[i];
					dfs(start+1,i+1);
					visit[i] = false;
				}
			}
		}
		
	}
}