Skip to content

Kth Row of Pascal's Triangle

Problem Description:

Given an index k, return the kth row of the Pascal's triangle.

Pascal's triangle: To generate A[C] in row R, sum up A'[C] and A'[C-1] from previous row R - 1.

Example:

Input : k = 3

Return : [1,3,3,1]

Note: k is 0 based. k = 0, corresponds to the row [1].

Note: Could you optimize your algorithm to use only O(k) extra space?

Solution

swift
import Foundation

class Solution {
	func getRow(_ A: inout Int) -> [Int] {
        if A <= 0 {
            return [1]
        }
        var result = [Int](repeating:0,count:A+1)
        result[0] = 1
        for i in 1...A{
            var prev = 1
            for j in 1...i {
                let new = prev + result[j]
                prev = result[j]
                result[j] = new
            }
        }
        return result
	}
}

References