문제
https://programmers.co.kr/learn/courses/30/lessons/12977
코딩테스트 연습 - 소수 만들기
주어진 숫자 중 3개의 수를 더했을 때 소수가 되는 경우의 개수를 구하려고 합니다. 숫자들이 들어있는 배열 nums가 매개변수로 주어질 때, nums에 있는 숫자들 중 서로 다른 3개를 골라 더했을 때
programmers.co.kr
풀이
백트래킹으로 해결할 수 있었다. nums의 모든 요소에 대해 n개 중 3개를 뽑는 조합을 만들어주고 조합이 완성되면 소수 판별 함수를 통해 소수인지 아닌지 판별해주었다.
코드
#include <vector>
using namespace std;
int result = 0;
int arr[1001];
bool isused[1001];
bool isPrimeNumber(int n)
{
if (n == 1)
{
return false;
}
else if (n == 2)
{
return true;
}
for (int i = 3; i <= n - 1; i++)
{
if (n % i == 0)
{
return false;
}
}
return true;
}
void func(int idx, int cnt, vector<int> nums)
{
int temp = 0;
if (cnt == 3)
{
for (int i = 0; i < 3; i++)
{
temp += arr[i];
}
if (isPrimeNumber(temp))
{
result++;
}
return;
}
for (int i = idx; i < nums.size(); i++)
{
if (!isused[nums[i]])
{
isused[nums[i]] = true;
arr[cnt] = nums[i];
func(i + 1, cnt + 1, nums);
isused[nums[i]] = false;
}
}
}
int solution(vector<int> nums) {
int answer = -1;
func(0, 0, nums);
answer = result;
return answer;
}
'프로그래머스' 카테고리의 다른 글
[프로그래머스] 프로그래머스 Level2 게임 맵 최단거리 C++ (0) | 2022.05.02 |
---|---|
[프로그래머스] 프로그래머스 Level1 로또의 최고 순위와 최저 순위 C++ (데브매칭 코딩테스트) (0) | 2022.05.02 |
[프로그래머스] 프로그래머스 Level2 가장 큰 수 C++ (0) | 2022.05.01 |
[프로그래머스] 프로그래머스 Level2 카카오프렌즈 컬러링북 C++ (카카오 코딩테스트) (0) | 2022.05.01 |
[프로그래머스] 프로그래머스 Level2 피보나치 수 C++ (0) | 2022.05.01 |