Skip to content

Instantly share code, notes, and snippets.

@omo

omo/Solution.kt Secret

Created July 30, 2022 12:56
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/2985f51256817fbef1ce1e33f9e94cb8 to your computer and use it in GitHub Desktop.
Save omo/2985f51256817fbef1ce1e33f9e94cb8 to your computer and use it in GitHub Desktop.
fun memo(f: (n: Int) -> Int) : (n: Int) -> Int {
val hash = HashMap<Int,Int>()
return fun (n: Int) : Int {
if (!hash.contains(n)) { hash[n] = f(n) }
return hash[n] ?: throw RuntimeException("Souldn't happen")
}
}
class Solution {
fun climbStairs(n: Int): Int {
var search : (n: Int) -> Int = { throw RuntimeException("Shouldn't happen 2") }
search = memo {
when (it) {
1 -> 1
2 -> 2
else -> search(it - 1) + search(it - 2)
}
}
return search(n)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment