Memoization
분할정복
# Python
def fibonacci(num):
if num <= 1:
return num
return fibo(num - 1) + fibo(num - 2)
// Swift
func fibonacci(_ n: Int) -> Int {
if n <= 1 {
return n
}
return fibonacci(n-1) + fibonacci(n-2)
}
# Python
def fibonacci_dp(num):
cache = [0 for _ in range(num+1)] # 하위값들을 저장할 list
cache[0] = 0 # 피보나치수열 초기값 저장
cache[1] = 1 # 피보나치수열 초기값 저장
for i in range(2, num+1):
cache[i] = cache[i-1]+cache[i-2] # 반복해서 저장
return cache[num]
// Swift
func fibonacciDp(_ n: Int) -> Int {
var cache = (0...n).map { $0 * 0 }
cache[0] = 0
cache[1] = 1
for i in 2...n {
cache[i] = cache[i-1] + cache[i-2]
}
return cache[n]
}