<청춘> 격정적으로 사는 것

밤을 새고 공부한 다음 날 새벽에 느꼈던 생생한 환희와 야생적인 즐거움을 잊을 수 없다

코딩테스트/백준

[백준] 15649번, 15650번 : N과 M (1), (2), (3), (4) / 파이썬 Python / 백트래킹

수학도 2021. 5. 26. 13:55

 

모든 경우를 탐색하는 백트래킹 알고리즘

 

 

itertools / permutations / combinations

 

2021.05.26 - [파이썬 Python] - [파이썬 Python] itertools , 순열과 조합 (permutations, combinations)

 

 

join

2021.05.26 - [파이썬 Python] - [파이썬 Python] split / join 함수 : 리스트의 문자열 합치기 나누기

 

 


 

N과 M (1)

 

 


내 코드

 

 

 

from itertools import permutations

N, M = map(int, input().split())

P = permutations(range(1, N+1), M)

for p in P :
    print(' '.join(map(str, p)))

 

 

 

N과 M (2)

 

 


내 코드

 

 

from itertools import combinations

n, m = map(int, input().split())

c = combinations(range(1,n+1), m)

for i in c :
    print(' '.join(map(str, i)))

 

N과 M (3)

 

 


내 코드

from itertools import product

n, m = map(int, input().split())

P = product(range(1, n+1), repeat=m)

for p in P:
    print(" ".join(map(str, p)))

 

N과 M (4)

 

 


내 코드

 

 

from itertools import combinations_with_replacement

n, m = map(int, input().split())

C = combinations_with_replacement(range(1, n+1), m)

for c in C:
    print(" ".join(map(str, c)))

 

 

 

 

출처

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

 

15649번: N과 M (1)

한 줄에 하나씩 문제의 조건을 만족하는 수열을 출력한다. 중복되는 수열을 여러 번 출력하면 안되며, 각 수열은 공백으로 구분해서 출력해야 한다. 수열은 사전 순으로 증가하는 순서로 출력해

www.acmicpc.net