[백준] 15651번 N과 M (3)

거북이·2023년 1월 18일
0

백준[실버3]

목록 보기
13/92
post-thumbnail

💡문제접근

  • 중복을 허용하는 중복 순열 문제다. 각각의 유형에 대해 사용할 수 있는 itertools패키지를 정리하면 아래와 같다.
종류패키지명
순열permutations
조합combinations
중복순열product
중복조합combinations_with_replacement

💡코드(메모리 : 30616KB, 시간 : 1940ms)

import itertools

N, M = map(int, input().split())
arr = [i for i in range(1, N+1)]

data = itertools.product(arr, repeat=M)
for i in data:
    print(*i)

📌백트래킹 풀이 방법(메모리 : 31256KB, 시간 : 1408ms)

import sys
input = sys.stdin.readline

N, M = map(int, input().strip().split())
li = []

def recursive():
    if len(li) == M:
        print(" ".join(map(str, li)))
        return 0
    else:
        for i in range(1, N+1):
            li.append(i)
            recursive()
            li.pop()
recursive()
  • 중복순열을 이용하는 문제였다. 리스트에 1이 있어도 그 다음 1을 넣을 수 있는 것이다. if문을 사용하지 않고 appendpop를 이용해서 해결할 수 있었다. 점점 감이 잡히는 것 같다.

💡소요시간 : 3m

0개의 댓글