Skip to content

Commit 4d08db4

Browse files
authored
Create fibonacciMemoization.swift
1 parent 513070d commit 4d08db4

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

src/swift/fibonacciMemoization.swift

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)