posted by 코딩 공부중 2022. 2. 7. 14:57

한자리 숫자가 적힌 종이 조각이 흩어져있습니다. 흩어진 종이 조각을 붙여 소수를 몇 개 만들 수 있는지 알아내려 합니다.

각 종이 조각에 적힌 숫자가 적힌 문자열 numbers가 주어졌을 때, 종이 조각으로 만들 수 있는 소수가 몇 개인지 return 하도록 solution 함수를 완성해주세요.

제한사항

  • numbers는 길이 1 이상 7 이하인 문자열입니다.
  • numbers는 0~9까지 숫자만으로 이루어져 있습니다.
  • "013"은 0, 1, 3 숫자가 적힌 종이 조각이 흩어져있다는 의미입니다.

입출력 예

numbersreturn

"17" 3
"011" 2

입출력 예 설명

예제 #1
[1, 7]으로는 소수 [7, 17, 71]를 만들 수 있습니다.

예제 #2
[0, 1, 1]으로는 소수 [11, 101]를 만들 수 있습니다.

  • 11과 011은 같은 숫자로 취급합니다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import java.util.*;
 
class Solution {
    static int answer = 0;
    static List<Integer> result = new ArrayList<>();
    
    public static void cal(int n){
        if(n == 0return;
        if(n == 1return;
        for(int i=2;i<=Math.sqrt(n);i++){
            if(n % i == 0return;
        }
        answer++;
    }
    
    
    void perm(String numbers,int[] tmp,int[] output,boolean[] isVisit,int depth, int limit,int count){
        if(count==0){
            String sum = "";
            for(int i=0; i< output.length; i++){
                if(!numbers.contains(Integer.toString(output[i]))){
                    continue;
                } else {
                    sum= sum + Integer.toString(output[i]);
                }
                result.add(Integer.parseInt(sum));
            }
            return;
        } 
        for(int i=0; i<limit; i++){
            if(!isVisit[i]){
               isVisit[i] = true;
               output[depth] = tmp[i];
               perm(numbers,tmp,output, isVisit, depth+1, limit, count-1);
               isVisit[i] = false;
            }
        }
        
    }
    
    public int solution(String numbers) {
        String[] param = {};
         param = numbers.split("");
        int[] tmp = new int[param.length];
        int[] output = new int[param.length];
        for(int i=0; i<param.length; i++){
            tmp[i] = Integer.parseInt(param[i]);
        }
        int limit = tmp.length;
        boolean[] isVisit = new boolean[limit];
       
        for(int cnt=1; cnt<=limit; cnt++) {
            perm(numbers,tmp,output, isVisit, 0, limit, cnt);
        }
        Set<Integer> set = new HashSet<>(result);
        
        for(int i : set){
            cal(i);
        } 
        
        return answer;
    }
}
cs

완전탐색으로 풀어야 함 재귀함수로 해결

'java' 카테고리의 다른 글

[프로그래머스]큰 수 만들기  (0) 2022.02.07
[프로그래머스]카펫  (0) 2022.02.07
[프로그래머스]더 맵게  (0) 2022.02.07
[프로그래머스]카카오인턴 - 키패드누르기  (0) 2020.09.24
(프로그래머스)가장 큰 수  (0) 2020.09.17