DFS 방식으로 순열 만들기
public class NUM42839 {
public static void main(String[] args) {
String numbers = "1753";
System.out.println(solution(numbers));
}
public static int solution(String numbers) {
int answer = 0;
ArrayList<String> numberList = new ArrayList<>(Arrays.asList(numbers.split("")));
HashSet<Integer> permutations = new HashSet<>();
for(int i = 0; i < numberList.size(); i++) {
Collections.sort(numberList);
String current = numberList.remove(i);
// System.out.println("numberList.remove = " + current);
addPermutation(numberList, permutations, current);
// System.out.println("numberList.add = " + current);
numberList.add(current);
}
for(Integer p : permutations) { if(isPrime(p)) { answer++; } }
return answer;
}
public static void addPermutation(ArrayList<String> numberList, HashSet<Integer> permutations, String current) {
// System.out.println("permutations.add = " + current);
permutations.add(Integer.parseInt(current));
for(int i = 0; i < numberList.size(); i++) {
String next = numberList.remove(0);
// System.out.println("numberList.remove = " + next);
addPermutation(numberList, permutations, current + next);
numberList.add(next);
// System.out.println("numberList.add = " + next);
}
}
public static boolean isPrime(int number) {
if(number <= 1 || (number != 2 && number % 2 == 0)) { return false; }
for(int i = 3; i <= Math.sqrt(number); i+=2) { if(number % i == 0) { return false; } }
return true;
}
}
*다른 분들의 코드를 참고하여 작성했습니다