[프로그래머스] 모음사전 | C++

Algorithm/문제풀이

2023. 1. 12. 11:26


문제

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

주어진 단어가 사전 순으로 몇 번째인지 구하는 문제였다.

 

나의 풀이 전략

DFS로 푼다.

 

상세

1. DFS 함수의 이름은 makeCombination()이다.

우리가 조합한 단어는 comb, 문제에서 주어진 단어는 dest, 재귀깊이는 depth로 설정한다.

더보기
void makeCombination(string comb, string dest, int depth) // DFS
{

}

 

2. 우리가 이용할 모음은 정해져있다. 상수 문자 배열로 고정해주자.

더보기
// 전역
const char vowSet[5] = {'A', 'E', 'I', 'O', 'U'};

 

3. vowSet을 일순하며 comb에 모음을 넣으면서 count를 한다.

combdest와 일치하면 countanswer로 넣는다.

그리고 다음 재귀로 진입한다.

재귀탈출 후 다음 comb를 위해 마지막 글자를 빼준다.

더보기
int count = 0;
int answer = 0;

void makeCombination(string comb, string dest, int depth) // DFS
{
    for(int i = 0; i < 5; ++i)
    {
        comb.push_back(vowSet[i]); count++;
        if(comb == dest) answer = count;
        makeCombination(comb, dest, depth + 1);
        comb.pop_back();
    }
}

 

4. 기저조건을 설정한다.

더보기
void makeCombination(string comb, string dest, int depth) // DFS
{
    if(depth == 5) return;

    for(int i = 0; i < 5; ++i)
    {
        comb.push_back(vowSet[i]); count++;
        if(comb == dest) answer = count;
        makeCombination(comb, dest, depth + 1);
        comb.pop_back();
    }
}

 

전체 소스코드

#include <string>
#include <vector>
using namespace std;

const char vowSet[5] = {'A', 'E', 'I', 'O', 'U'};

int count = 0;
int answer = 0;

void makeCombination(string comb, string dest, int depth) // DFS
{
    if(depth == 5) return;

    for(int i = 0; i < 5; ++i)
    {
        comb.push_back(vowSet[i]); count++;
        if(comb == dest) answer = count;
        makeCombination(comb, dest, depth + 1);
        comb.pop_back();
    }
}

int solution(string word)
{
    makeCombination("", word, 0);

    return answer;
}