[백준] 15649~15652번 - N과 M Python 파이썬

Miin·2022년 12월 16일
0

Algorithm

목록 보기
3/4

백트래킹 문제를 풀다보니 15649번부터 15652번 문제가 모두 itertools를 써서 간단하게 해결할 수 있어서 한꺼번에 다뤄보려 한다.

15649번 - N과 M (1)

📄 문제


❗️풀이

순열(Permutation)
: 순서를 고려하여 뽑는 경우의 수

from itertools import permutations
# 순열을 구할 itertator와 조합의 개수를 parameter로 받음
print(permutations([1,2,3], 2)

#결과
(1,2)
(1,3)
(2,1)
(2,3)
(3,1)
(3,2)

✏️ 코드

import sys
from itertools import permutations
input = sys.stdin.readline

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

for a in permutations(map(str, range(1,N+1)),M):
    print(' '.join(a))

itertools 생각 못하고 재귀로 풀었다가 시간이 대략 10배정도 차이가 났다,,, 그래도 스스로 풀이 완료!


15650번 - N과 M (2)

📄 문제


❗️풀이

조합(Combination)
: 순서를 고려하지 않고 뽑는 경우의 수

from itertools import combinations
# 조합을 구할 itertator와 조합의 개수를 parameter로 받음
print(combinations([1,2,3], 2)

#결과
(1,2)
(1,3)
(2,3)

✏️ 코드

import sys
from itertools import combinations
input = sys.stdin.readline

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

for a in combinations(map(str,range(1,N+1)), M):
    print(*a)

스스로 풀이 완료!


15651번 - N과 M (3)

📄 문제


❗️풀이

중복순열(Permutation with Repetition → Product)
: 순서를 고려하여 뽑는 경우의 수 (중복 가능)

from itertools import product
# 중복 순열을 구할 itertator와 조합의 개수(repeat)를 parameter로 받음
print(product([1,2,3], repeat = 2))

#결과
(1,1)
(1,2)
(1,3)
(2,1)
(2,2)
(2,3)
(3,1)
(3,2)
(3,3)

✏️ 코드

import sys
from itertools import product
input = sys.stdin.readline

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

for a in product(map(str,range(1,N+1)), repeat = M):
    print(' '.join(a))

스스로 풀이 완료!


15651번 - N과 M (4)

📄 문제

❗️풀이

중복조합(Combination with Repetition)
: 순서를 고려하지 않고 뽑는 경우의 수 (중복 가능)

from itertools import combinations_with_replacement
# 중복 조합을 구할 itertator와 조합의 개수를 parameter로 받음
print(combinations_with_replacement([1,2,3], 2))

#결과
(1,1)
(1,2)
(1,3)
(2,2)
(2,3)
(3,3)

✏️ 코드

import sys
from itertools import combinations_with_replacement
input = sys.stdin.readline 

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

for a in combinations_with_replacement(map(str,range(1,N+1)), M):
    print(' '.join(a))

스스로 풀이 완료!

profile
Today Miin Learned

0개의 댓글