-
-
Save omo/2985f51256817fbef1ce1e33f9e94cb8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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