Skip to content

Commit d726708

Browse files
committed
[BOJ] #1759.암호 만들기 / 골드5 / 30(O)
1 parent 6c9f2e2 commit d726708

File tree

3 files changed

+60
-16
lines changed

3 files changed

+60
-16
lines changed

.gitignore

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
.cph/
22
.DS_Store
3-
.DS_Store
3+
.vscode/

learntosurf/Backtracking/2025-04-14-[BOJ]-#1759-암호만들기.py

Lines changed: 33 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -6,21 +6,39 @@
66
chars = input().split()
77
chars.sort() # 오름차순 정렬
88

9-
candidates = list(combinations(chars, L)) # L개 고르는 모든 조합을 생성
10-
11-
# 조건에 맞는 조합 필터링
12-
# 조건: 모음 >= 1개, 자음 >= 2개
139
vowels = set('aeiou')
10+
result = []
1411

15-
for comb in candidates:
16-
vowel_count = 0
17-
consonant_count = 0
18-
19-
for ch in comb:
20-
if ch in vowels:
21-
vowel_count += 1
22-
else:
23-
consonant_count += 1
12+
# 백트래킹: 해를 찾는 도중 해가 아니어서 막히면, 되돌아가서 다시 해를 찾아가는 기법
13+
# 현재까지 만든 암호의 길이가 L이면 종료 조건
14+
# 모음/자음 개수를 체크해서 만족할 경우 출력
15+
# 그렇지 않으면 다음 알파벳을 선택해 재귀 호출
16+
def backtrack(path, start):
17+
# 1. 종료 조건: 길이가 L이면 조합 완성
18+
if len(path) == L:
19+
vowel_count = 0
20+
consonant_count = 0
21+
22+
# 모음/자음 개수 세기
23+
for ch in path:
24+
if ch in vowels:
25+
vowel_count += 1
26+
else:
27+
consonant_count += 1
28+
29+
# 조건에 맞으면 출력
30+
if vowel_count >= 1 and consonant_count >= 2:
31+
print(''.join(path))
32+
return
2433

25-
if vowel_count >= 1 and consonant_count >= 2:
26-
print(''.join(comb))
34+
# 2. 가능한 모든 문자에 대해 선택
35+
for i in range(start, C): # C == len(chars)
36+
# 선택
37+
path.append(chars[i])
38+
# 재귀 호출(다음 문자 선택) - 조합이므로 i+1부터
39+
backtrack(path, i+1)
40+
# 선택 취소
41+
path.pop()
42+
43+
# 탐색 시작
44+
backtrack([], 0)
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import sys
2+
input = sys.stdin.readline
3+
from itertools import combinations
4+
5+
L, C = map(int, input().split())
6+
chars = input().split()
7+
chars.sort() # 오름차순 정렬
8+
9+
candidates = list(combinations(chars, L)) # L개 고르는 모든 조합을 생성
10+
11+
# 조건에 맞는 조합 필터링
12+
# 조건: 모음 >= 1개, 자음 >= 2개
13+
vowels = set('aeiou')
14+
15+
for comb in candidates:
16+
vowel_count = 0
17+
consonant_count = 0
18+
19+
for ch in comb:
20+
if ch in vowels:
21+
vowel_count += 1
22+
else:
23+
consonant_count += 1
24+
25+
if vowel_count >= 1 and consonant_count >= 2:
26+
print(''.join(comb))

0 commit comments

Comments
 (0)