Post

[백준/코틀린] 11050번: 이항 계수 1

브론즈 1

링크

11050번: 이항 계수 1

풀이

조합을 재귀적으로 구현하고, 메모이제이션을 통해 중복 계산을 방지합니다.

코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
val combinationCache = List(11) { MutableList(11) { 0 } }
fun combination(n: Int, k: Int): Int {
    if (combinationCache[n][k] != 0) return combinationCache[n][k]

    return when {
        k == 0 || k == n -> 1
        else -> combination(n - 1, k - 1) + combination(n - 1, k)
    }.also { combinationCache[n][k] = it }
}

fun main() {
    val (n, k) = readln().split(" ").map { it.toInt() }

    println(combination(n, k))
}

This post is licensed under CC BY 4.0 by the author.