728x90
반응형
import sys
input = sys.stdin.readline
# 중복 없으며 뒷 숫자가 더 커야 한다
N, M = map(int, input().split())
numbers = list(map(int, input().split()))
numbers.sort()
box = []
def compare(a, b):
if a >= b:
return False
return True
def backTracking(depth):
if depth == M:
print(' '.join(map(str, box)))
return
for i in range(N):
if depth == 0 or (numbers[i] not in box and compare(box[depth-1], numbers[i])):
box.append(numbers[i])
backTracking(depth + 1)
box.pop()
backTracking(0)
N과 M 문제를 계속 풀다보니 각 문제가 뭐가 다른건지 점점 헷갈린다.
수열을 생성할 때 중복 숫자는 안 되고 뒷 숫자가 더 커야 한다.
뒷 숫자가 더 큰지 확인하는 compare 함수를 만들고,
depth가 0일 때는 수열에 숫자 추가,
0이 아닐 때는 중복 숫자가 아닌지 and 뒷 숫자가 더 큰지 확인한 후 수열에 추가한다.
수열이 완성되면(depth가 최대에 도달하면) join으로 공백을 추가해서 즉시 출력해준다.
728x90
반응형
'Algorithm > BackTracking' 카테고리의 다른 글
[Baekjoon 15657 / Python / 실버3] N과 M (8) (0) | 2024.08.07 |
---|---|
[Baekjoon 15656 / Python / 실버3] N과 M (7) (0) | 2024.08.07 |
[Baekjoon 15654 / Python / 실버3] N과 M (5) (1) | 2024.08.07 |
[Baekjoon 15652 / Python / 실버3] N과 M (4) (0) | 2024.08.07 |
[Baekjoon 15651 / Python / 실버3] N과 M (3) (0) | 2024.08.07 |