For Programmer

백준 1759번 파이썬 문제풀이(브루트 포스 - 암호 만들기) 본문

코팅테스트/백준 문제 모음

백준 1759번 파이썬 문제풀이(브루트 포스 - 암호 만들기)

유지광이 2021. 10. 20. 15:59
728x90

 

코드

L, C = map(int, input().split())
alphabet = list(map(str, input().split()))
alphabet.sort()  # 알파벳 오름차순 정렬
out = []
vowel = ['a', 'e', 'i', 'o', 'u']  # 모음 세팅


def solve(depth, idx):
    if depth == L:
        vo = 0  # 모음 개수
        co = 0  # 자음 개수
        for i in range(len(out)):
            if out[i] in vowel:  # 출력할 알파벳에 모음이 있는지 없는지 체크
                vo += 1  # 모음이 있으면 +1
            else:  # 모음이 아니라면
                co += 1  # 자음에 +1
        if vo >= 1 and co >= 2:  # 모음이 1개 이상이고 자음이 2개 이상이라면
            print(''.join(out))  # 출력
        return
    for i in range(idx, C):
        out.append(alphabet[i])  # 출력 리스트에 추가
        solve(depth + 1, i + 1)  # 재귀를 돈다
        out.pop()  # 출력 함수에서 제거


solve(0, 0)

-> 위 문제는 기본적으로 15652번 문제하고 비슷하다. 다른 점은 모음과 자음 개수를 세서 개수가 조건에 맞으면 출력한다는 점만 기억하면 된다. 밑의 코드는 이 조건을 찾지못해 일일이 조건들을 수기로 분기를 하였으며 방문처리를 할 필요도 없는데 굳이 방문처리를 한 코드이다.

 

나의 코드

L, C = map(int, input().split())
alphabet = list(map(str, input().split()))
alphabet.sort()
out = []
visited = [False] * (C + 1)
vowel = ['a', 'e', 'i', 'o', 'u']


def solve(depth, idx):
    if depth == L:
        count = 0
        for i in vowel:
            if i in out:
                count += 1
        if 0 < count <= 1 and len(out) == 3:
            print(''.join(out))
        elif 0 < count <= 2 and len(out) == 4:
            print(''.join(out))
        elif 0 < count <= 3 and len(out) == 5:
            print(''.join(out))
        elif 0 < count <= 4 and len(out) == 6:
            print(''.join(out))
        elif 0 < count <= 5 and len(out) == 7:
            print(''.join(out))
        elif 0 < count and len(out) >= 8:
            print(''.join(out))
        return
    for i in range(idx, C):
        if not visited[i]:
            visited[i] = True
            out.append(alphabet[i])
            solve(depth + 1, i + 1)
            visited[i] = False
            out.pop()


solve(0, 0)

 

728x90
Comments