본문 바로가기

Study/Programmers

프로그래머스 - 소수 찾기

소수를 찾는 것은 쉬우나, 문자열을 입력받아 해당 문자들로 만들 수 있는 모든 수의 조합을 찾는 것을 재귀로 짜보려했으나 잘 되지 않았다. 그래서 next_permutation을 사용했다.

 

코드

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
#include <string>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
map<intint> m;
int answer;
int find(int num)
{
    if (num < 2)
        return (0);
    if (num == 2 || num == 3)
        return (1);
    int i = 2;
    while (i * i <= num)
    {
        if (num % i == 0)
            return (0);
        i++;   
    }
    return (1);
}
 
int solution(string numbers) {
    int len = numbers.size();
    vector<bool> pv(numbers.size(), false);
    for(int i = 1; i <= len; i++){
        std::fill(pv.begin(), pv.end(), false);
        std::fill(pv.end() - i, pv.end(), true);
        do{
            string tmp;
            for(size_t j = 0; j < len; j++){
                if(pv[j]){
                    tmp += numbers[j];
                }
            }
            sort(tmp.begin(), tmp.end());
            do{
                int num = stoi(tmp);
                if(find(num) && !m[num])
                {
                    answer++;
                    m[num]++;
                }
            }while(next_permutation(tmp.begin(), tmp.end()));
        }while(next_permutation(pv.begin(), pv.end()));
    }
    return answer;
}
cs

pv는 pick vector로 어떤 idx의 문자를 고를 것인지에 대한 정보를 담은 vector이다.

반복문을 1 ~ len만큼 반복시켜, pv가 선택하는 개수도 1 ~ len개가 되게 하였다.

pv배열을 이용하여 어떤 문자들이 골라졌는지 string에 모두 모아놓고 tmp에 대해 next_permutation하면 문자열 조합이 모두 나오게 된다. 

즉, 이중 next_permutation을 사용하면 문자열에서 주어진 문자를 이용하여 만들 수 있는 모든 수의 조합을 구할 수 있다.

이 때 중복 처리의 경우에는 map을 이용하여 해결하였다. 

 

'Study > Programmers' 카테고리의 다른 글

프로그래머스 - 섬 연결하기  (0) 2021.04.14
프로그래머스 - 여행 경로  (0) 2021.04.14
프로그래머스 - 단어 변환  (0) 2021.04.13
프로그래머스 - 타겟 넘버  (0) 2021.04.13
프로그래머스 - 가장 큰 수  (0) 2021.04.13