알고리즘
[Java] 백준 15650번 N과 M (2)
J3SUNG
2023. 1. 23. 23:58
728x90
https://j3sung.tistory.com/834
[Java] 백준 15649번 N과 M (1)
수열이 주어지고 크기가 주어질때 가능한 조합의 수를 전부 출력하는 문제입니다. DFS를 사용해서 모든 경우의 수를 확인해주었습니다. 출력이 많아서 Java에서 시간초과가 발생하여 BufferedWriter
j3sung.tistory.com
위의 문제와 비슷한 문제입니다. 다른 점은 조합이 수열이 중복되면 안된다는 점입니다.
ex) 1 2 3 4
4 3 2 1 (위의 경우와 중복)
DFS를 사용해 완전탐색을 진행하였으며
DFS내에서 반복문을 현재 다음위치부터로 진행해서 중복된 수열이 나오지 않게 했습니다.
import java.io.*;
import java.util.Scanner;
public class Main {
public static int[] arr;
public static boolean[] visit;
public static int n;
public static int m;
public static BufferedWriter bf;
public static void main(String argc[]) throws IOException{
bf = new BufferedWriter(new OutputStreamWriter(System.out));
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
arr = new int[m];
visit = new boolean[n];
for(int i=0; i<n; ++i){
DFS(i, 0);
}
bf.close();
}
public static void DFS(int num, int cnt) throws IOException{
visit[num] = true;
arr[cnt] = num + 1;
if(m == cnt+1){
for(int i=0; i<m; ++i) {
bf.write(arr[i] + " ");
}
bf.write("\n");
visit[num] = false;
return;
}
for(int i=num; i<n; ++i){
if(!visit[i]){
DFS(i, cnt+1);
}
}
visit[num] = false;
}
}