import java.util.*;
class Solution {
public int solution(String[] spell, String[] dic) {
Set<String> wordSet = new HashSet<>(Arrays.asList(dic));
Arrays.sort(spell);
List<String> wordList = new ArrayList<>();
generateCombinations("", spell, wordList);
for (String word : wordList) {
if (wordSet.contains(word)) {
return 1;
}
}
return 2;
}
private void generateCombinations(String current, String[] spell, List<String> combinations) {
if (current.length() == spell.length) {
combinations.add(current);
return;
}
for (int i = 0; i < spell.length; i++) {
if (i > 0 && spell[i].equals(spell[i - 1])) {
continue;
}
if (!current.contains(spell[i])) {
generateCombinations(current + spell[i], spell, combinations);
}
}
}
}
- wordSet 변수는 dic 배열에서 중복된 값을 제거하여 Set으로 생성합니다.
- spell 배열을 Arrays.sort() 메소드를 이용하여 사전순으로 정렬합니다.
- wordList 변수는 조합을 저장할 ArrayList입니다. generateCombinations() 메소드를 이용하여
spell 배열의 모든 조합을 생성하여 wordList에 추가합니다.
- for 문을 이용하여 wordList에 저장된 각 조합이 wordSet에 있는지 검사합니다.
조합이 wordSet에 있다면 1을 리턴하고, 없다면 2를 리턴합니다.
- generateCombinations() 메소드는 재귀함수를 이용하여 spell 배열의 모든 조합을 생성합니다.
current 변수에 현재까지 생성된 문자열을 저장하고, spell 배열에서 중복된 알파벳을 건너뛰며 재귀호출합니다.