티스토리 뷰

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


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


프로그래머스 링크 - https://programmers.co.kr/learn/courses/30/lessons/42839?language=java


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
64
65
66
67
68
69
70
import java.util.*;
class Solution {
    
    static private int n; // nPr의 n
    static private int r; // nPr의 r
    static private String[] res;
    static private ArrayList<String> alist = new ArrayList<>();
    static private HashSet<Integer> map = new HashSet<>();
 
    static public void swap(String[] arr, int i, int j) {
        String temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
 
    static public void perm(String[] arr, int depth) {
 
        // depth가 0부터 시작했을 경우 depth == r에서 리턴
        if (depth == r) {
            String temp = "";
            for (String item : res) {
                temp += item;
            }
           if (Integer.parseInt(temp) <=1) {
                return;
            }
            map.add(Integer.parseInt(temp));
            return;
        }
 
        for (int i = depth; i < n; i++) {
            swap(arr, depth, i);     // 스왑
            res[depth] = arr[depth]; // 선택된 원소 저장
            perm(arr, depth + 1);     // 재귀호출
            swap(arr, depth, i);     // 복원
        }
    }
    public int solution(String numbers) {
        
        String[] arr = new String[numbers.length()];
        for (int i = 0; i < numbers.length(); i++) {
            arr[i] = numbers.substring(i, i+1);
        }
 
        for (int i = 1; i <= arr.length; i++) {
            int select = i;
            n = arr.length;
            r = select;
            res = new String[r];
            perm(arr, 0);
        }
 
        int cnt = 0;
 
 
        for (int item : map) {
               boolean flag = true;
            for (int j = 2; j * j <= item; j++) {
                if (item % j == 0) {
                    flag = false;
                    break;
                }
            }
            if (flag == true) cnt++;
 
        }
        
        return cnt;
    }
}
cs


공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/04   »
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
글 보관함