뚱땅뚱땅

[문제] 백준 15664번 N과 M (10) - Java 본문

알고리즘/백준

[문제] 백준 15664번 N과 M (10) - Java

양순이 2021. 7. 13. 21:26
728x90

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

 

15664번: N과 M (10)

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

www.acmicpc.net

조합문제다.

HashSet을 사용해서 중복되는 수열이 있는지 검사해주었다.

생각해보니, 저렇게 set을 이용할 거라면 그냥 list를 사용해도 될 것 같다.

 

public class Main {
	static int N,M;
	static int[] arr;
	static StringBuilder sb = new StringBuilder();
	static HashSet<String> set = new HashSet<>();
	
	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);
		// 조합
		comb(0, new int[M], 0);
		
		System.out.println(sb);
		
	}
	static void comb(int cnt, int[] selected, int startIdx) {
		if(cnt == M) {
			StringBuilder tmp = new StringBuilder();
			for(int i=0;i<cnt;i++) {
				tmp.append(selected[i]).append(' ');
			}
			tmp.append('\n');
			String str = tmp.toString();
			if(!set.contains(str)) {
				set.add(str);
				sb.append(tmp);
			}
			return;
		}
		for(int i=startIdx;i<N;i++) {
			selected[cnt] = arr[i];
			comb(cnt+1, selected, i+1);
		}
	}
}
728x90
Comments