BJ15666 N과 M (12)

·2022년 5월 11일
0

백준 알고리즘

목록 보기
33/34

https://www.acmicpc.net/problem/15666

정렬, 중복 제거 후에 순열 재귀함수를 이용하면 원하는 출력을 얻을 수 있다.


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

public class NandM {
	static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
	static StringTokenizer st;
	static int N, M;
	static int[] num, input;
	static void permutation(int start, int cnt) throws IOException {
		if(cnt == M) {
			for(int i = 0; i < M; i++) {
				bw.append(num[i] + "");
				if(i != M - 1) {
					bw.append(" ");
				}
			}
			bw.append("\n");
			return;
		}
		
		for(int i = start; i < N; i++) {
			num[cnt] = input[i];
			permutation(i, cnt + 1);
		}
		
	}
	public static void main(String[] args) throws IOException {
		st = new StringTokenizer(br.readLine());
		N = Integer.parseInt(st.nextToken());
		M = Integer.parseInt(st.nextToken());
		input = new int[N];
		num = new int[M];
		st = new StringTokenizer(br.readLine());
		for(int i = 0; i < N; i++) {
			input[i] = Integer.parseInt(st.nextToken());
		}
		
		Arrays.sort(input);
		
		// 중복 제거
		for(int i = 1; i < N; i++) {
			if(input[i] == input[i - 1]) {
				int j = i;
				while(j < N - 1) {
					input[j] = input[j++ + 1];
				}
				i--;
				N--;
			}
		}
		permutation(0, 0);
	//	System.out.println(Arrays.toString(input));
		bw.flush();
	}
}
profile
SSAFY 7기

0개의 댓글