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

[BOJ/Step14] 15650 : N๊ณผ M (2) (Python)

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

www.acmicpc.net/problem/15650

 

15650๋ฒˆ: N๊ณผ M (2)

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

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 ๊ฐ€ ์žˆ๋Š”์ง€ ํ™•์ธํ•˜์—ฌ ์žˆ์œผ๋ฉด continue => ์ค‘๋ณต ์—†์ด m๊ฐœ์˜ ์ˆ˜๋ฅผ ๊ณ ๋ฅด๊ธฐ ๋•Œ๋ฌธ

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

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

    5. ์•„๋‹ˆ๋ฉด 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):
        if i in seq[:index]:
            continue
        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ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•

# 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(nm, m))
for i in a:
    print(' '.join(i))

 

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

์ถœ๋ ฅํ•˜๋Š” ์ˆ˜์—ด ์ˆ˜๊ฐ€ ์ค„์–ด๋“œ๋‹ˆ๊นŒ ์‹œ๊ฐ„๋„ ํ™• ์ค„์—ˆ๋‹ค