[Algorithm][Python] 백준(BOJ) 6603 로또 (Silver 2)

최대 1 분 소요

[문제]

https://www.acmicpc.net/problem/6603

image image image


풀이

백트래킹 문제이다. combinations 라이브러리를 사용하여 풀었는데, dfs를 이용하여 푸는 방법도 알아둬야 한다.

combinations 라이브러리 활용한 코드

from itertools import combinations

while True:
    nums = list(map(int,input().split()))
    if nums[0] == 0:
        break
    else:
        k = nums[0]
        for x in combinations(nums[1:], 6):
            print(*x)
        print()

dfs(재귀) 를 활용한 코드

def dfs(start, depth):
    if depth == 6:
        print(*result)
        return
    for i in range(start, k):
        result.append(nums[i])
        dfs(i+1, depth+1)
        result.pop()

while True:
    nums = list(map(int,input().split()))
    result = []
    if nums[0] == 0:
        break
    else:
        k = nums[0]
        nums = nums[1:]
        dfs(0,0)
        print()


image

댓글남기기