뚱땅뚱땅

[문제] 백준 15655번 N과 M (6) - Java 본문

알고리즘/백준

[문제] 백준 15655번 N과 M (6) - Java

양순이 2021. 7. 13. 20:09
728x90

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

 

15655번: N과 M (6)

N개의 자연수와 자연수 M이 주어졌을 때, 아래 조건을 만족하는 길이가 M인 수열을 모두 구하는 프로그램을 작성하시오. N개의 자연수는 모두 다른 수이다. N개의 자연수 중에서 M개를 고른 수열

www.acmicpc.net

조합 문제임은 자명하다.

여기서 오름차순으로 출력하라고 되어있으므로 애초에 배열을 오름차순 정렬시켜준다.

public class Main {
	static int N,M;
	static int[] arr;
	static StringBuilder sb = new StringBuilder();
	
	public static void main(String[] args) throws IOException {
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(in.readLine()," ");
		N = Integer.parseInt(st.nextToken());
		M = Integer.parseInt(st.nextToken());
		
		arr = new int[N];
		st = new StringTokenizer(in.readLine(), " ");
		for(int i=0;i<N;i++) {
			arr[i] = Integer.parseInt(st.nextToken());
		} // 배열 초기화
		
		// 수열은 사전순으로 증가해야하므로 배열을 초기에 오름차순으로 정렬
		Arrays.sort(arr);
		
		// 중복 x , 조합
		comb(0, new int[M], 0);
		System.out.print(sb);
	}
	static void comb(int cnt, int[] selected, int startIdx) {
		if(cnt == M) {
			for(int i=0;i<cnt;i++) {
				sb.append(selected[i]).append(' ');
			}
			sb.append('\n');
			return;
		}
		for(int i=startIdx;i<N;i++) {
			selected[cnt]= arr[i];
			comb(cnt+1, selected, i+1);
		}
	}
}
728x90
Comments