728x90

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

 

15651번: N과 M (3)

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

www.acmicpc.net

 

python에는 중복순열이 따로 있지 않지만 itertools product로 구현할 수 있다. 

import  itertools 

n,m = map(int, input().split())
perm = [iter for iter in itertools.product(range(1,n+1), repeat=m)]
for p in perm:
    print(' '.join(map(str, p)))

dfs알고리즘을 이용한 코드 

n, m = map(int, input().split())
back = []

def dfs():
    if len(back) == m:
        print(' '.join(map(str, back)))
        return
        
    for i in range(1, n+1):
        back.append(i)
        dfs()
        back.pop()

dfs()

dfs코드가 itertools보다 메모리, 시간 모두 효율적이였는데 특히 메모리에서 큰 차이를 보였다. 

728x90

'Algorithm > 백준' 카테고리의 다른 글

[백준] 10973 이전순열  (0) 2023.03.17
[백준] 10972 다음순열  (0) 2023.03.17
[백준] 15650 n과 m 2  (0) 2023.03.15
[백준] 15649 n과 m 1  (0) 2023.03.15
[백준] 16922 로마 숫자 만들기  (0) 2023.03.06

+ Recent posts