Skip to content

Instantly share code, notes, and snippets.

@omo

omo/Solution.kt Secret

Created July 30, 2022 13:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save omo/3988803de8bb938c1f1b1825eda41173 to your computer and use it in GitHub Desktop.
Save omo/3988803de8bb938c1f1b1825eda41173 to your computer and use it in GitHub Desktop.
class Memo(val f: Memo.(n: Int) -> Int) {
val hash = HashMap<Int, Int>()
operator fun invoke(n: Int) : Int {
if (!hash.contains(n)) { hash[n] = this.f(n) }
return hash[n] ?: throw RuntimeException("Souldn't happen")
}
}
class Solution {
fun climbStairs(n: Int): Int {
val search = Memo {
when (it) {
1 -> 1
2 -> 2
else -> this(it - 1) + this(it - 2)
}
}
return search(n)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment