Skip to content

Instantly share code, notes, and snippets.

@cbruegg
Created November 22, 2015 20:06
Show Gist options
  • Save cbruegg/375ea0ee27c6bc7b484f to your computer and use it in GitHub Desktop.
Save cbruegg/375ea0ee27c6bc7b484f to your computer and use it in GitHub Desktop.
val numberOfBSTs = hashMapOf(
0 to 1.0,
1 to 1.0,
2 to 2.0
)
fun numberOfBSTs(nodes: Int): Double =
when (nodes) {
in numberOfBSTs -> numberOfBSTs[nodes]!!
else -> ((1..nodes)
.sumByDouble { numberOfBSTs(it - 1) * numberOfBSTs(nodes - it) })
.apply { numberOfBSTs[nodes] = this }
}
fun main(args: Array<String>) {
(1..100)
.asSequence()
.map { "There are ${numberOfBSTs(it)} BSTs for $it nodes" }
.forEach { println(it) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment