[프로그래머스] Level.2 완전탐색- 소수찾기

2021. 1. 19. 15:23Algorithm/프로그래머스

 

코딩테스트 연습 - 소수 찾기

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

programmers.co.kr

 

문제설명

 

입출력예

 

 

 

 

 

https://yabmoons.tistory.com/336 분의 소수찾기와 순열 조합게시물을 참고해서 풀었다 ㅠㅠ

 

[ 프로그래머스 소수 찾기 (Lv2) ] (C++)

프로그래머스의 소수찾기(Lv2) 문제이다. [ 문제풀이 ] 1) 본인은 이 문제를 부분집합의 개념으로 접근해 보았다.   주어진 문자열에서, 구할 수 있는 모든 원소들을 순열의 개념으로 뽑으면서 그

yabmoons.tistory.com

 

#include<string>
#include<vector>
#include<cmath>

using namespace std;

bool visited[10000000];
bool use[10];
int total;

bool isprime(int n)
{
	if (n == 0 || n == 1) return false;
	for (int i = 2; i <= sqrt(n); i++){
		if (n % i == 0) return false;
	}
	return true;
}

void findNumber(int cnt, string numbers, string temp)
{
	if (temp != "" && visited[stoi(temp)] == false){
		int Num = stoi(temp);
		visited[Num] = true;
		if (isprime(Num) == true) total++;
	}

	for (int i = 0; i < numbers.length(); i++) {
		if (use[i] == true) continue;
		use[i] = true;
		findNumber(cnt + 1, numbers, temp + numbers[i]);
		use[i] = false;
	}
}

int solution(string numbers)
{
	findNumber(0, numbers, "");
	return total;
}