We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 513070d commit 4d08db4Copy full SHA for 4d08db4
src/swift/fibonacciMemoization.swift
@@ -0,0 +1,23 @@
1
+// Memoization dictionary to store computed Fibonacci numbers
2
+var memo: [Int: Int] = [:]
3
+
4
+// Function to calculate Fibonacci numbers using memoization
5
+func fibonacciMemoization(_ n: Int) -> Int {
6
+ if n <= 1 {
7
+ return n
8
+ }
9
10
+ // Check if the result is already memoized
11
+ if let cachedResult = memo[n] {
12
+ return cachedResult
13
14
15
+ // Calculate Fibonacci recursively and store the result in memoization
16
+ let result = fibonacciMemoization(n - 1) + fibonacciMemoization(n - 2)
17
+ memo[n] = result
18
19
+ return result
20
+}
21
22
+let index: Int = 15
23
+print("Fibonacci (memoization):", fibonacciMemoization(index))
0 commit comments