Dynamic programming is a method used in computer science to solve complex problems by breaking them down into simpler subproblems. It is especially useful for optimization problems where the solution can be built incrementally. In Swift, you can implement dynamic programming patterns using arrays, dictionaries, or any data structure that allows storage of intermediate results. Below is an example of dynamic programming in Swift for calculating the Fibonacci sequence.
func fibonacci(_ n: Int, memo: inout [Int?]) -> Int {
if n <= 1 {
return n
}
if let result = memo[n] {
return result
}
memo[n] = fibonacci(n - 1, memo: &memo) + fibonacci(n - 2, memo: &memo)
return memo[n]!
}
func fibonacciDynamic(_ n: Int) -> Int {
var memo = Array(repeating: nil, count: n + 1)
return fibonacci(n, memo: &memo)
}
// Example usage
print(fibonacciDynamic(10)) // Output: 55
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?