find the nth catalan number in swift

The nth Catalan number can be calculated using either recursion or dynamic programming. Here's how to do it in Swift using recursion:

main.swift
func catalanNumber(_ n: Int) -> Int {
    if n <= 1 {
        return 1
    }
    
    var res = 0
    for i in 0..<n {
        res += catalanNumber(i) * catalanNumber(n - i - 1)
    }
    return res
}
201 chars
12 lines

Here's how to do the same thing using dynamic programming, which is more efficient:

main.swift
func catalanNumber(_ n: Int) -> Int {
    var catalan = [Int](repeating: 0, count: n + 1)
    catalan[0] = 1
    
    for i in 1...n {
        for j in 0..<i {
            catalan[i] += catalan[j] * catalan[i - j - 1]
        }
    }
    return catalan[n]
}
258 chars
12 lines

Both functions take an integer n as input and return the nth Catalan number.

gistlibby LogSnag