백트래킹 관련 문제를 찾다가 풀이한 문제입니다.
itertools의 permutation으로 풀면 더 쉬울 것 같은데, 목적이 있어 백트래킹으로 제출했습니다.
코드와 설명 참고.
https://veggie-garden.tistory.com/24
[Python] 백트래킹 (+ DFS와 차이)
백트래킹이란? 백트래킹이란 현재 상태에서 가능한 모든 경로를 따라 들어가 탐색하다, 원하는 값과 불일치하는 부분이 발생하면 더 이상 탐색을 진행하지 않고 전 단계로 돌아가는, 즉 이름 그
veggie-garden.tistory.com
/ 백트래킹 /
# 백트래킹 구현
n, m = map(int, input().split())
ans = []
def back():
if len(ans) == m:
print(" ".join(map(str,ans)))
return
for i in range(1, n + 1):
if i not in ans:
ans.append(i)
back()
ans.pop()
back()
/ itertools의 permutations 사용 /
# permutations 사용
from itertools import permutations
import sys
input = sys.stdin.readline
n, m = map(int, input().split())
result = permutations(range(1,n+1), m)
for res in result:
for i in res:
print(i, end=" ")
print("")
'CodingTest > Baekjun Online Judge' 카테고리의 다른 글
[ BOJ / 파이썬 ] 2178 미로 탐색 (0) | 2022.07.23 |
---|---|
[ BOJ / 파이썬] 1926 그림 (0) | 2022.07.23 |
[ BOJ ] 스타트와 링크 (0) | 2022.07.19 |
[ BOJ ] 구슬 탈출 2 (0) | 2022.07.19 |
[ 백준 / BOJ ] 2064 IP주소 * 다시 풀기 * (0) | 2022.07.01 |