본문 바로가기

알고리즘 공부

[BOJ] 로또(6603) 문제 풀기 | Python3

 


문제 풀이)

집합 K에서 수 6개를 조합할 수 있는 경우를 모두 출력하는 문제입니다. 파이썬 내장 모듈 itertools.combinations 를 사용하면 훨씬 간단하지만 백트래킹 알고리즘을 사용해 문제를 풀어보고싶어 dfs함수를 사용하였습니다.

 

문제 코드)

 

1
2
3
4
5
6
7
8
9
10
11
12
def dfs(depth, sequence):
    if depth==6:
        print(*[numbers[i]for i in sequence[1:]], sep=' ')
        return
    for i in range(sequence[-1]+1, n):
        dfs(depth+1, sequence+[i])
 
while True:
    n, *numbers=map(int, input().split())
    if n==0: break
    dfs(0,[-1])
    print()
cs