๊ธ€ ์ž‘์„ฑ์ž: ์ด์ง€์›๐ŸŒฉ๏ธ

์ข…๋งŒ๋ถ์˜ ์˜ˆ์‹œ๋ฅผ ์ฐธ๊ณ ํ•˜์—ฌ ํ’€๊ณ  ์žˆ๋Š”๋ฐ, ๋™์ผํ•œ ์ฝ”๋“œ์ž„์—๋„ ๋ถˆ๊ตฌํ•˜๊ณ  ์Šค์œ„ํ”„ํŠธ์—์„œ๋Š” ์‹œ๊ฐ„ ์ดˆ๊ณผ, ํŒŒ์ด์ฌ์—์„œ๋Š” ํ†ต๊ณผ๋˜๋Š” ๊ธฐ๋ฌ˜ํ•œ ํ˜„์ƒ์ด ์žˆ์—ˆ๋‹ค. ์›๋ž˜ ์ฝ”๋“œ๋Š” ๋งค๊ฐœ ๋ณ€์ˆ˜๋กœ picked ๋ฐฐ์—ด์„ inout์œผ๋กœ ๋ฐ›๊ณ  ์žˆ์—ˆ๋Š”๋ฐ, ์ด๊ฒƒ์ด ๋ฌธ์ œ์˜€๋‹ค. ๋„์›€์„ ์ฃผ์‹  ํƒํ˜„๋‹˜๊ป˜ ์ด ์ž๋ฆฌ๋ฅผ ๋นŒ์–ด ๊ฐ์‚ฌ์˜ ๋ง์”€์„ ๋“œ๋ฆฐ๋‹ค. ๐Ÿ™ ์›์ธ ์ฐพ๋Š”๋‹ค๊ณ  1์‹œ๊ฐ„์„ ํ—ค๋งธ๋‹ค. ํ‘ํ‘

๋ฌธ์ œ

https://www.acmicpc.net/problem/15651


๋‚ด๊ฐ€ ์ž‘์„ฑํ•œ ์ฝ”๋“œ

Swift

let input = readLine()!.split(separator: " ").map { Int(String($0))! }
let n = input[0]
let m = input[1]

var picked = [Int]()
/*
 n: ์ „์ฒด ์›์†Œ์˜ ์ˆ˜
 picked: ์ง€๊ธˆ๊นŒ์ง€ ๊ณ ๋ฅธ ์›์†Œ๋“ค์˜ ๋ฒˆํ˜ธ
 toPick: ๋” ๊ณ ๋ฅผ ์›์†Œ์˜ ์ˆ˜
 ์ผ ๋•Œ, ์•ž์œผ๋กœ toPick๊ฐœ์˜ ์›์†Œ๋ฅผ ๊ณ ๋ฅด๋Š” ๋ชจ๋“  ๋ฐฉ๋ฒ•์„ ์ถœ๋ ฅํ•œ๋‹ค
 */
func pick(n: Int, picked:inout [Int], toPick: Int) {
    // ๊ธฐ์ € ์‚ฌ๋ก€: ๋” ๊ณ ๋ฅผ ์›์†Œ๊ฐ€ ์—†์„ ๋•Œ ๊ณ ๋ฅธ ์›์†Œ๋“ค์„ ์ถœ๋ ฅํ•œ๋‹ค.
    if toPick == 0 {
        for p in picked {
            print(p, terminator: " ")
        }
        print()
        return
    }
    // ์›์†Œ ํ•˜๋‚˜๋ฅผ ๊ณ ๋ฅธ๋‹ค.
    for next in 1...n {
        picked.append(next)
        pick(n: n, picked: &picked, toPick: toPick - 1)
        picked.removeLast()
    }
}

pick(n: n, picked: &picked, toPick: m)

Python

import sys
n, m = map(int, sys.stdin.readline().split())
picked = []

"""
 n: ์ „์ฒด ์›์†Œ์˜ ์ˆ˜
 picked: ์ง€๊ธˆ๊นŒ์ง€ ๊ณ ๋ฅธ ์›์†Œ๋“ค์˜ ๋ฒˆํ˜ธ
 toPick: ๋” ๊ณ ๋ฅผ ์›์†Œ์˜ ์ˆ˜
 ์ผ ๋•Œ, ์•ž์œผ๋กœ toPick๊ฐœ์˜ ์›์†Œ๋ฅผ ๊ณ ๋ฅด๋Š” ๋ชจ๋“  ๋ฐฉ๋ฒ•์„ ์ถœ๋ ฅํ•œ๋‹ค
"""
def pick(n: int, picked: [int], toPick: int):
    # ๊ธฐ์ € ์‚ฌ๋ก€: ๋” ๊ณ ๋ฅผ ์›์†Œ๊ฐ€ ์—†์„ ๋•Œ ๊ณ ๋ฅธ ์›์†Œ๋“ค์„ ์ถœ๋ ฅํ•œ๋‹ค.
    if toPick == 0:
        print(*picked)
        return
    # ์›์†Œ ํ•˜๋‚˜๋ฅผ ๊ณ ๋ฅธ๋‹ค.
    for next in range(1, n+1):
        picked.append(next)
        pick(n, picked, toPick - 1)
        picked.pop()

pick(n, picked, m)
๋ฐ˜์‘ํ˜•