Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 스프링 컨테이너와 스프링 빈
- 코틸린인액션
- 코틀린
- 스프링 핵심 원리 이해
- 7장 고급매핑
- kotlin in action 정리
- 스프링 핵심 원리 - 기본편
- 객체 지향 설계와 스프링
- 컨베이어 벨트 위의 로봇 Python
- 기능개발 python
- 백준 13460 Python
- 백준 20055 컨베이어 벨트 위의 로봇
- Kotlin In Action
- 자바 ORM 표준 JPA 프로그래밍 7장
- Kotlin in action 6장
- Python
- Kotlin
- KotlinInAction
- Kotlin in action 10장
- 백준
- 코틀린인액션
- 13460 구슬탈출 2
- 고급매핑
- Kotlin in action 5장
- 20055
- Kotlin in action 3장
- 싱글톤 컨테이너
- 20055 컨베이어 벨트 위의 로봇
- spring
- 스프링 핵심 원리
Archives
- Today
- Total
기록하는 습관
[프로그래머스] 완전탐색 - 소수 찾기 본문
문제 설명
한자리 숫자가 적힌 종이 조각이 흩어져있습니다. 흩어진 종이 조각을 붙여 소수를 몇 개 만들 수 있는지 알아내려 합니다.
각 종이 조각에 적힌 숫자가 적힌 문자열 numbers가 주어졌을 때, 종이 조각으로 만들 수 있는 소수가 몇 개인지 return 하도록 solution 함수를 완성해주세요.
제한사항
- numbers는 길이 1 이상 7 이하인 문자열입니다.
- numbers는 0~9까지 숫자만으로 이루어져 있습니다.
- 013은 0, 1, 3 숫자가 적힌 종이 조각이 흩어져있다는 의미입니다.
입출력 예
numbers return
17 | 3 |
011 | 2 |
입출력 예 설명
예제 #1
[1, 7]으로는 소수 [7, 17, 71]를 만들 수 있습니다.
예제 #2
[0, 1, 1]으로는 소수 [11, 101]를 만들 수 있습니다.
- 11과 011은 같은 숫자로 취급합니다.
해결 알고리즘
1. 각 숫자들의 순열을 구한다.
2. 소수 판별하기
#include <string>
#include <vector>
#include <set>
using namespace std;
using Primes = set<int, greater<int>>;
bool isPrime(int number, Primes& primes) {
if (number <= 1) {
return false;
}
if (primes.find(number) != primes.end()) {
return true;
}
for (int i = 2; i < number; ++i){
if ((number % i) ==0) {
return false;
}
}
primes.insert(number);
return true;
}
void dfs(const string& numbers, const string& currentNumber,int index, int r, vector<bool>& visited, Primes& primes) {
if (currentNumber.size() == r) {
const int number = stoi(currentNumber);
if (isPrime(number, primes)) {
return;
}
}
const int numberCount = numbers.size();
for (int i = 0; i < numberCount; ++i) {
if (!visited[i]) {
visited[i] = true;
const string newNumber = currentNumber + numbers[i];
dfs(numbers, newNumber, i, r, visited, primes);
visited[i] = false;
}
}
}
int solution(string numbers) {
const int numberCount = numbers.size();
Primes primes;
vector<bool> visited(numberCount, false);
for (int r = 1; r <= numberCount; ++r) {
dfs(numbers, "", 0, r, visited, primes);
}
const int answer = primes.size();
return answer;
}
'알고리즘 > [문제풀이] 프로그래머스' 카테고리의 다른 글
[프로그래머스] 연습문제 - 2016년 (0) | 2020.03.04 |
---|---|
[프로그래머스] 탐욕법(Greedy) - 체육복 (0) | 2020.03.03 |
[프로그래머스] 정렬 - k번째수 (0) | 2020.03.03 |
[프로그래머스] 해시 - 완주하지 못한 선수 (0) | 2020.03.02 |
[프로그래머스] 완전탐색 - 모의고사 (0) | 2020.01.06 |
Comments