Created
May 11, 2019 13:37
-
-
Save pavel-sazonov/8dc242d3592fd023a5d13e1e48136104 to your computer and use it in GitHub Desktop.
swift fibonacci
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
// 1. Recursive approach | |
func fib(_ n: Int) -> Int { | |
guard n > 1 else { return n } | |
return fib(n-1) + fib(n-2) | |
} | |
// Time Complexity: O(2^n) | |
// Space Complexity: O(2^n) | |
// 2. Iterative approach | |
func fib(_ n: Int) -> Int { | |
var fibs: [Int] = [1, 1] | |
(2...n).forEach { i in | |
fibs.append(fibs[i - 1] + fibs[i - 2]) | |
} | |
return fibs.last! | |
} | |
// Time Complexity: O(n) | |
// Space Complexity: O(n) | |
// 3. Iterative approach — Optimized | |
func fib(_ n: Int) -> Int { | |
var a = 1 | |
var b = 1 | |
guard n > 1 else { return a } | |
(2...n).forEach { _ in | |
(a, b) = (a + b, a) | |
} | |
return a | |
} | |
// Time Complexity: O(n) | |
// Space Complexity: O(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment