BOJ : N과 M (12) [15666]

1. 문제


N개의 자연수와 자연수 M이 주어졌을 때, 아래 조건을 만족하는 길이가 M인 수열을 모두 구하는 프로그램을 작성하시오.

N개의 자연수 중에서 M개를 고른 수열
같은 수를 여러 번 골라도 된다.
고른 수열은 비내림차순이어야 한다.
길이가 K인 수열 A가 A1 ≤ A2 ≤ ... ≤ AK-1 ≤ AK를 만족하면, 비내림차순이라고 한다.

출처 : https://www.acmicpc.net/problem/15666

2. 아이디어


  • combinations_with_replacement

    combinations_with_replacement를 이용해서 중복 조합 구하기

3. 코드


mine

from itertools import combinations_with_replacement

n,m = map(int, input().split())
result = set()
inputList = list(map(int, input().split()))
inputList.sort()

for i in combinations_with_replacement(inputList, m):
    if i not in result:
        result.add(i)
        print(' '.join(map(str, i)))

someone

from itertools import combinations_with_replacement

n, m = map(int, input().split())
inputlist = list(map(int, input().split()))
inputlist.sort()
arr = list(combinations_with_replacement(inputlist, m))
arr = sorted(list(set(arr)))

for i in arr:
  print(*i)

출처 : https://it-garden.tistory.com/164

좋은 웹페이지 즐겨찾기