알고리즘
[Swift] 백준 2309번 일곱 난쟁이
고고
2022. 3. 18. 10:27
링크: https://www.acmicpc.net/problem/2309
2309번: 일곱 난쟁이
아홉 개의 줄에 걸쳐 난쟁이들의 키가 주어진다. 주어지는 키는 100을 넘지 않는 자연수이며, 아홉 난쟁이의 키는 모두 다르며, 가능한 정답이 여러 가지인 경우에는 아무거나 출력한다.
www.acmicpc.net
people로 9명의 난쟁이를 입력받습니다.
조합 함수로 총 7명의 난쟁이를 뽑고, 합계가 100이라면 결과를 업데이트합니다.
import Foundation
var people = [Int]()
for _ in 0..<9 {
people.append(Int(readLine()!)!)
}
var result = [Int]()
func combination(_ index: Int, _ nowCombi: [Int]) {
if nowCombi.count == 7 {
if nowCombi.reduce(0, +) == 100 {
result = nowCombi
}
return
}
for i in index..<people.count {
combination(i + 1, nowCombi + [people[i]])
}
}
combination(0, [])
result.sorted().forEach { print($0) }