한자리 숫자가 적힌 종이 조각이 흩어져있습니다. 흩어진 종이 조각을 붙여 소수를 몇 개 만들 수 있는지 알아내려 합니다.
각 종이 조각에 적힌 숫자가 적힌 문자열 numbers가 주어졌을 때, 종이 조각으로 만들 수 있는 소수가 몇 개인지 return 하도록 solution 함수를 완성해주세요.
numbers | return |
---|---|
"17" | 3 |
"011" | 2 |
[1, 7]으로는 소수 [7, 17, 71]를 만들 수 있습니다.
[0, 1, 1]으로는 소수 [11, 101]를 만들 수 있습니다.
*11과 011은 같은 숫자로 취급합니다.
import java.util.*;
class Solution {
public static char[] card;
public static boolean[] visited;
public static HashSet<Integer> set;
public int solution(String numbers) {
visited = new boolean[numbers.length()];
card = numbers.toCharArray();
set = new HashSet<>();
dfs(0, "");
return set.size();
}
public static void dfs(int depth, String num){
if(depth == visited.length){
if(num.equals("")){
return;
}
int temp = Integer.parseInt(num);
if(isPrime(temp)){
set.add(temp);
}
return;
}
for (int i = 0; i < card.length; i++) {
if(!visited[i]){
visited[i] = true;
dfs(depth + 1, num + card[i]);
visited[i] = false;
dfs(depth + 1, num);
}
}
}
public static boolean isPrime(int n){
if(n <= 1) return false;
for (int i = 2; i <= Math.sqrt(n); i++) {
if(n % i == 0){
return false;
}
}
return true;
}
}
글 재미있게 봤습니다.