์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ฌธ์ œ/BOJ_Python

[BOJ/Step14] 15652 : N๊ณผ M (4) (Python)

NaNaRin๐Ÿ™ƒ 2021. 2. 20. 15:20

www.acmicpc.net/problem/15652

 

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

ํ•œ ์ค„์— ํ•˜๋‚˜์”ฉ ๋ฌธ์ œ์˜ ์กฐ๊ฑด์„ ๋งŒ์กฑํ•˜๋Š” ์ˆ˜์—ด์„ ์ถœ๋ ฅํ•œ๋‹ค. ์ค‘๋ณต๋˜๋Š” ์ˆ˜์—ด์„ ์—ฌ๋Ÿฌ ๋ฒˆ ์ถœ๋ ฅํ•˜๋ฉด ์•ˆ๋˜๋ฉฐ, ๊ฐ ์ˆ˜์—ด์€ ๊ณต๋ฐฑ์œผ๋กœ ๊ตฌ๋ถ„ํ•ด์„œ ์ถœ๋ ฅํ•ด์•ผ ํ•œ๋‹ค. ์ˆ˜์—ด์€ ์‚ฌ์ „ ์ˆœ์œผ๋กœ ์ฆ๊ฐ€ํ•˜๋Š” ์ˆœ์„œ๋กœ ์ถœ๋ ฅํ•ด

www.acmicpc.net


1~N ์ค‘ M๊ฐœ์˜ ์ˆ˜๋ฅผ ๊ณจ๋ผ ๋น„๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ์ถœ๋ ฅํ•˜๋Š” ๋ฌธ์ œ

 

(1) ๋ฆฌ์ŠคํŠธ์— ๋ฏธ๋ฆฌ m๊ฐœ๋งŒํผ์˜ 0์„ ์ €์žฅํ•œ ํ›„ index ์ˆœ์„œ๋Œ€๋กœ ์ฑ„์›Œ๋„ฃ์œผ๋ฉฐ ์ถœ๋ ฅํ•˜๋Š” ๋ฐฉ๋ฒ•

  def sequence( seq, n, m, index ) :

    1. i๊ฐ€ seq[index-1] ~ N๊นŒ์ง€ ๋ฐ˜๋ณต => ์ด์ „ ์œ„์น˜(์™ผ์ชฝ)์˜ ์ˆ˜๋ณด๋‹ค ํฐ ์ˆ˜๋งŒ. ๋น„๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ์ถœ๋ ฅํ•ด์•ผํ•˜๊ณ  ์ด๋ฏธ ๋‚˜์™”๋˜ ์ˆ˜์—ด์ผ ๊ฒƒ์ด๊ธฐ ๋•Œ๋ฌธ

    2. ๋ฆฌ์ŠคํŠธ seq[index]์— i ๋Œ€์ž…

    3. index+1 == m์ด๋ฉด seq๋ฅผ ์ถœ๋ ฅ

    4. ์•„๋‹ˆ๋ฉด sequence( seq, n, m, index+1 ) ํ˜ธ์ถœ

# 15650-1.py

def sequence(seq, n, m, index):
    for i in range(seq[index-1] if seq[index-1] != 0 else 1, n+1):
        seq[index] = i
        if index + 1 == m:
            print(' '.join(map(str, seq)))
        else:
            sequence(seq, n, m, index+1)


n, m = map(int, input().split())
nm = [0 for _ in range(m)]
sequence(nm, n, m, 0)

 

(2) itertools ๋ชจ๋“ˆ์˜ combinations_with_replacementํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•

# 15650-2.py

import itertools

n, m = map(int, input().split())
nm = [str(i) for i in range(1, n+1)]

a = list(itertools.combinations_with_replacement(nm, m))
for i in a:
    print(' '.join(i))

 

์œ„๋ถ€ํ„ฐ (2) (1)๋ฒˆ ์ฝ”๋“œ

์™œ์ธ์ง€ ์ด๋ฒˆ์—” ์‹œ๊ฐ„์ด ๋น„์Šทํ•˜๋‹ค

๋ชจ๋“ˆ ํ•จ์ˆ˜๋ฅผ ๋น„์Šทํ•˜๊ฒŒ ์ฝ”๋“œ๊ฐ€ ์งœ์ง„๊ฑธ๊นŒ ? ใ…Žใ…Žใ…Ž