forked from igorwojda/kotlin-coding-challenges
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.kt
27 lines (21 loc) · 783 Bytes
/
Solution.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package com.igorwojda.integer.fibonacci.recursivecached
private object Solution1 {
private data class MethodCache(val n: Int, val result: Int)
private fun fibonacciSequenceRecursiveCached(
n: Int,
methodCache: MutableList<MethodCache> = mutableListOf(),
): Int {
var result = methodCache.firstOrNull { it.n == n }?.result
if (result == null) {
if (n < 2) {
methodCache.add(MethodCache(n, n))
return n
}
result = fibonacciSequenceRecursiveCached(n - 1, methodCache) +
fibonacciSequenceRecursiveCached(n - 2, methodCache)
methodCache.add(MethodCache(n, result))
}
return result
}
}
private object KtLintWillNotComplain