📝 코테/BOJ

[Swift] 백준 9095 1, 2, 3 더하기

JerryiOS 2023. 4. 14. 04:03

import Foundation

let T = Int(readLine()!)!

for _ in 0..<T{
    let n = Int(readLine()!)!
    
    print(dp(n))
}

func dp(_ n: Int) -> Int {
    var cache: [Int] = [1, 2, 4]
    
    guard n > 2 else { return n }
    
    for num in 3...n {
        cache.append(cache[num - 3] + cache[num - 2] + cache[num - 1])
    }
    
    return cache[n-1]
}
반응형