DFS(int idx, ArrayList<Character> vowel, ArrayList<Character> consonant){
if(선택된 개수 == L){
출력
}else{
조합을 구한다(모음이면 vowel, 자음이면 consonant에 넣는다)
}
}
조합에서 하나의 문자를 선택할지, 말지에 따라 2갈래가 생긴다. 최대 후보 개수 C ≤ 15 이다.
최대 2^15 = 32768 이므로, 제한 시간내에 계산 가능하다.
import java.util.*;
public class Main {
//모음 리스트
static char[] vowelList = {'a', 'e', 'i', 'o', 'u'};
//입력 받을 변수 전역으로 선언
static int L, C;
static char[] input;
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
//입력 받기
L = scanner.nextInt();
C = scanner.nextInt();
input = new char[C];
for(int i=0; i<C; i++) input[i] = scanner.next().charAt(0);
Arrays.sort(input);
//조합을 구하는 DFS
DFS(0, new ArrayList<>(), new ArrayList<>());
}
static void DFS(int idx, ArrayList<Character> vowel, ArrayList<Character> consonant){
//암호 개수 충족
if(vowel.size() + consonant.size()==L) {
//암호 조건 검사
if (vowel.size() >= 1 && consonant.size() >= 2) {
ArrayList<Character> out = new ArrayList<>();
out.addAll(vowel);
out.addAll(consonant);
Collections.sort(out); //출력전 정렬
for (Character c : out) {
System.out.print(c);
}
System.out.println();
}
return;
}else {
//조합을 구한다.
for (int i = idx; i < C; i++) {
if (isVowel(i)) { //모음인 경우
vowel.add(input[i]);
DFS(i + 1, vowel, consonant);
vowel.remove(vowel.size()-1);
} else { //자음인 경우
consonant.add(input[i]);
DFS(i + 1, vowel, consonant);
consonant.remove(consonant.size() - 1);
}
}
}
}
// 해당 idx의 input이 모음인지 확인하는 함수
private static boolean isVowel(int currentInputIndex) {
boolean isVowel = false;
for (char v : vowelList) {
if (v == input[currentInputIndex]) {
isVowel = true;
break;
}
}
return isVowel;
}
}