뚱땅뚱땅

[문제] 백준 15650번 N과 M (2) - Java 본문

알고리즘/백준

[문제] 백준 15650번 N과 M (2) - Java

양순이 2021. 7. 13. 17:03
728x90

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

 

15650번: N과 M (2)

한 줄에 하나씩 문제의 조건을 만족하는 수열을 출력한다. 중복되는 수열을 여러 번 출력하면 안되며, 각 수열은 공백으로 구분해서 출력해야 한다. 수열은 사전 순으로 증가하는 순서로 출력해

www.acmicpc.net

 

간단한 조합 문제

public class Main {
	static int N, M;
	
	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());
		
		// 1~N 중 중복 없이 M 개를 고른 수열 && 오름차순 => 조합 nCm
		comb(0, new int[M], 0);
	}
	
	static void comb(int cnt, int[] selected, int startIdx) {
		if(cnt == M) {
			for(int i=0;i<cnt;i++) {
				System.out.print(selected[i]+ " ");
			}
			System.out.println();
			return;
		}// 기저조건
		
		for(int i=startIdx;i<N;i++) {
			selected[cnt] = i+1;
			comb(cnt+1, selected, i+1);
 		}
	}
}
728x90
Comments