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

๋‚˜๋Š” ์–ด๋–ค ์œ ํ˜•์˜ ์ •ํ˜•ํ™”๋œ ์ฝ”๋“œ๋ฅผ ์™ธ์šฐ๋ฉด, ๋Œ€๋ถ€๋ถ„์˜ ๋ฌธ์ œ๋ฅผ ๊ทธ ๋ฐฉ์‹์„ ์‘์šฉํ•ด์„œ ํ‘ผ๋‹ค. ๊ทธ๋ž˜์„œ ์ด ๋ฌธ์ œ๋„ ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๋น„ํšจ์œจ์ ์ธ ์ฝ”๋“œ๊ฐ€ ๋‚˜์™”๋‹ค. ์‹œ๊ฐ„์„ ๋ณด๋‹ˆ ๋‹ค๋ฅธ ๋ถ„์— ๋น„ํ•ด ์•ฝ 50๋ฐฐ๊ฐ€ ๋Š๋ ธ๋‹ค(…). ๊ทธ๋ž˜์„œ ๋” ๊ฐ„๊ฒฐํ•œ ์ฝ”๋“œ๊ฐ€ ๊ถ๊ธˆํ•ด์„œ ์‚ดํŽด๋ณด์•˜๋Š”๋ฐ, ๊ตณ์ด ๋ฐฐ์—ด์„ ์“ฐ์ง€ ์•Š๊ณ , ๋ณ€์ˆ˜์— ์ €์žฅํ•ด์„œ ์žฌ๊ท€๋ฅผ ๋„˜๊ธฐ๊ณ (?), ํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ํ•˜๋”๋ผ. ์•„๋ฌดํŠผ ์ด๊ฑด ๋‚˜์ค‘์— ๋‹ค์‹œ ํ’€์–ด๋ด์•ผ๊ฒ ๋‹ค.

๋ฌธ์ œ

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

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

Swift

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

var picked = [Int]()
var visited = Array(repeating: false, count: n)
func pick(toPick: Int, start: Int) {
    if toPick == 0 {
        if picked.reduce(0, +) == target {
            count += 1
        }
        return
    }
    for i in start..<n {
        if visited[i] {
            continue
        }
        visited[i] = true
        picked.append(nums[i])
        pick(toPick: toPick - 1, start: i + 1)
        picked.removeLast()
        visited[i] = false
    }
}

for i in 1...n {
    pick(toPick: i, start: 0)
    visited = Array(repeating: false, count: n)
}

print(count)
๋ฐ˜์‘ํ˜•