본문 바로가기
algorithm/coding test

프로그래머스 모음사전 파이썬

by su0a 2024. 2. 23.

완전탐색 알고리즘에 관한 문제이다. 이 문제는 permutations함수를 사용할 사용할 수 없고 재귀 함수를 이용해야 하는 문제이다. 

dfs를 돌면서 현재 값의 순서를 1씩 증가시켜주고 word와 동일한 단어가 되면 해당 단어의 순서를 ans에 넣어주었다.

 

ans=0
cnt=0
alphabet=['A','E','I','O','U']
def dfs(word,str): #arr에 알파벳 추가
    global alphabet,ans,cnt
    if str==word:
        ans=cnt  #현재 단어와 word값 일치시 정답에 현재단어순서(cnt)를 넣음
        return
    for i in range(len(alphabet)):
        if len(str)<5: #현재 단어 길이가 5보다 작아야 알파벳을 추가할 수 있음
            str+=alphabet[i] #현재 알파벳 추가 
            cnt+=1 #현재 단어 순서
            dfs(word,str) 
            str=str[:-1] #현재 알파벳 삭제
def solution(word):
    global ans,cnt
    dfs(word,'')
    return ans