[프로그래머스] 5주차_모음사전
문제 푼 날짜 : 2021-09-10
문제
문제 링크 : https://programmers.co.kr/learn/courses/30/lessons/84512
접근 및 풀이
아래의 생각대로 코드를 구현하였다.
- 1~5자리로 만들 수 있는 모든 단어를 구해준다. (백트래킹)
- 구해진 단어들을 오름차순으로 정렬해준다.
- 찾고싶은 단어의 위치를 find함수를 통해 찾아주고, 그 위치를 return해준다.
코드
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
string alpha = "AEIOU";
void makeWords(string candid, int len, vector<string> &v) {
if (candid.length() == len) {
v.push_back(candid);
return;
}
for (char ch : alpha) {
makeWords(candid + ch, len, v);
}
}
int solution(string word) {
int answer = 0;
vector<string> v;
for (int i = 1; i <= 5; i++) {
makeWords("", i, v);
}
sort(v.begin(), v.end());
auto it = find(v.begin(), v.end(), word);
answer = it - v.begin() + 1;
return answer;
}
결과
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
string alpha = "AEIOU";
void makeWords(string candid, int len, vector<string> &v) {
if (candid.length() == len) {
v.push_back(candid);
return;
}
for (char ch : alpha) {
makeWords(candid + ch, len, v);
}
}
int solution(string word) {
int answer = 0;
vector<string> v;
for (int i = 1; i <= 5; i++) {
makeWords("", i, v);
}
sort(v.begin(), v.end());
auto it = find(v.begin(), v.end(), word);
answer = it - v.begin() + 1;
return answer;
}
피드백
백트래킹 문제 더 풀어보기
Author And Source
이 문제에 관하여([프로그래머스] 5주차_모음사전), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@bestcoders/프로그래머스-5주차모음사전저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)