Skip to content

Instantly share code, notes, and snippets.

@pavel-sazonov
Created May 11, 2019 13:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pavel-sazonov/8dc242d3592fd023a5d13e1e48136104 to your computer and use it in GitHub Desktop.
Save pavel-sazonov/8dc242d3592fd023a5d13e1e48136104 to your computer and use it in GitHub Desktop.
swift fibonacci
// 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