[Programmers] Lv2. ๋ชจ์Œ ์‚ฌ์ „ | C++

2023. 6. 4. 19:34ใ†Coding Test/Programmers

๐Ÿ”—๋ฌธ์ œ ๋ณด๋Ÿฌ๊ฐ€๊ธฐ
 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

๐Ÿ‘จโ€๐Ÿ’ปํ’€์ด ๊ณผ์ •

 

๋ฐฑํŠธ๋ž˜ํ‚น(Backtracking)์„ ์ด์šฉํ•ด ์‚ฌ์ „ ์ˆœ์„œ๋Œ€๋กœ ๋‹จ์–ด๋ฅผ ์กฐํ•ฉํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ํ’€์—ˆ์Šต๋‹ˆ๋‹ค. 1)์•ŒํŒŒ๋ฒณ์„ ํ•˜๋‚˜์”ฉ ๋ถ™์ด๊ณ  ๋–ผ๋Š” ๊ณผ์ •์—์„œ ์ธ๋ฑ์Šค ๋ฒˆํ˜ธ๋ฅผ ์ฆ๊ฐ€์‹œํ‚ค๊ณ , 2)์›ํ•˜๋Š” ๋‹จ์–ด๋ฅผ ์ฐพ์œผ๋ฉด ํƒ์ƒ‰์„ ์ค‘์ง€ํ•˜๋„๋ก ๊ตฌํ˜„ํ•˜์˜€์Šต๋‹ˆ๋‹ค.

์žฌ๊ท€(Recursion)์™€ ๋ฐฑํŠธ๋ž˜ํ‚น(Backtracking) ๊ฐœ๋…์ด ์ฒ˜์Œ์—๋Š” ์ต์ˆ™ํ•˜์ง€ ์•Š์•„, ์ฝ”๋“œ๋กœ ๊ตฌํ˜„ํ•˜๊ธฐ ์–ด๋ ค์› ๋Š”๋ฐ ์ ์  ์—ฐ์Šตํ•˜๋‹ค ๋ณด๋‹ˆ ์ต์ˆ™ํ•ด ์ง€๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.

 

โœ๏ธ์†Œ์Šค ์ฝ”๋“œ ๋ฐ ๊ฒฐ๊ณผ

#include <string>
#include <vector>
using namespace std;
const int VOWEL_NUM = 5;
const char vowel[VOWEL_NUM] = { 'A', 'E', 'I', 'O', 'U' };
bool isFindingWord = false;

void CreateCombinationWords(const string& word, string targetWord, int& index)
{
    if (targetWord.length() == VOWEL_NUM)
        return;

    for (int i = 0; i < VOWEL_NUM; i++)
    {
        targetWord.push_back(vowel[i]);
        index++;
        if (targetWord.compare(word) == 0)
        {
            isFindingWord = true;
            break;
        }

        CreateCombinationWords(word, targetWord, index);
        if (isFindingWord)
            break;

        targetWord.pop_back();
    }
}

int GetWordIndex(const string& word)
{
    int index = 0;
    string targetWord = "";
    CreateCombinationWords(word, targetWord, index);
    return index;
}

int solution(string word) {
    return GetWordIndex(word);
}

 

์ œ์ถœ ๊ฒฐ๊ณผ

 

 

 

728x90
๋ฐ˜์‘ํ˜•