LeetCode – 119. Pascal’s Triangle II

題目連結: https://leetcode.com/problems/pascals-triangle-ii/

// Test cases:
// rowIndex:0  result: [1]
// rowIndex:1  result: [1,1]
// rowIndex:2  result: [1,2,1]
// Time complexity: O(n^2)  Note: (1+n)*n/2
func getRow(_ rowIndex: Int) -> [Int] {
    if rowIndex == 0 { return [1] }
    else if rowIndex == 1 { return [1,1] }
    else {
        var triangle: [[Int]] = Array(repeating: [Int](), count: rowIndex + 1)
        for i in 0 ..< (rowIndex + 1) {
            for j in 0 ..< (i+1) {
                if j == 0 || j == i {
                    triangle[i].append(1)
                } else {
                    let val = triangle[i-1][j] + triangle[i-1][j-1]
                    triangle[i].append(val)
                }
            }
        }
        return triangle[rowIndex]
    }
}

assert(getRow(0) == [1], "Error 1")
assert(getRow(1) == [1, 1], "Error 2")
assert(getRow(2) == [1, 2, 1], "Error 3")