[BaekJoon] ๋ฐฑ์ค€ 15652๋ฒˆ : N๊ณผ M (4)

Updated:

15652๋ฒˆ : N๊ณผ M (4)


๋ฐฑํŠธ๋ž˜ํ‚น ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์‚ฌ์šฉํ•˜๋ฉด ๋˜๋Š” ๋ฌธ์ œ์ด๋‹ค.

๋ฐฑํŠธ๋ž˜ํ‚น์ด๋ž€ DFS, BFS ๋กœ ํƒ์ƒ‰์„ ํ•˜๋ฉด์„œ ๋‚ด๊ฐ€ ์›ํ•˜๋Š” ์กฐ๊ฑด์— ๋งž์ง€ ์•Š๋Š” ๋…ธ๋“œ์— ๋ฐฉ๋ฌธํ–ˆ์„๊ฒฝ์šฐ ๋ถ€๋ชจ๋…ธ๋“œ๋กœ ๋˜๋Œ์•„๊ฐ€๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜์ด๋‹ค.

image

n = 3, m = 3 ์ธ ๊ฒฝ์šฐ๋กœ ์˜ˆ๋ฅผ ๋“ค์–ด๋ณด๋ฉด ๋งŒ์•ฝ 2์—์„œ 1๋กœ ๊ฐ€๋Š” ๊ฒฝ์šฐ ์กฐ๊ฑด์— ๋งž์ง€ ์•Š๊ธฐ ๋•Œ๋ฌธ์— ๋ฐ”๋กœ ๋ถ€๋ชจ๋กœ ๋Œ์•„๊ฐ„๋‹ค.


import sys


def DFS(index):
	global n, m, data, stack

	if len(stack) == m:
		print(*stack)
		return

	for i in range(index, n):
		if stack and data[i] < stack[-1]:
			continue
		stack.append(data[i])
		DFS(0)
		stack.pop()


n, m = map(int, sys.stdin.readline().rsplit())
data = [i for i in range(1, n + 1)]
stack = []
DFS(0)

์ถ”๊ฐ€๋กœ ๋ฆฌ์ŠคํŠธ๋ฅผ ์›์†Œ๋งŒ ์ถœ๋ ฅํ•˜๊ณ  ์‹ถ์€ ๊ฒฝ์šฐ print(*list) ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋œ๋‹ค.


import sys
from itertools import combinations_with_replacement


n, m = map(int, sys.stdin.readline().rsplit())
res = combinations_with_replacement(range(1, n+1), m)

for i in res:
	print(*i)

๋˜ combination_with_replacement ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๊ฐ™์€ ์ˆ˜๋ฅผ ์—ฌ๋Ÿฌ๋ฒˆ ๊ณ ๋ฅธ ์กฐํ•ฉ์„ ๋งŒ๋“ค์–ด์ค€๋‹ค.



Categories:

Updated:

Leave a comment