본문 바로가기

CodingTest/Baekjun Online Judge

[ BOJ ] 15649 N과 M

백트래킹 관련 문제를 찾다가 풀이한 문제입니다.

 

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("")