Skip to content

Pascal Triangle

Problem Description

Given an integer A, equal to numRows, generate the first numRows of Pascal's triangle.

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

Problem Constraints

0 <= A <= 25
0 <= A <= 25

Input Format

The first argument is an integer A, equal to the numRows.
The first argument is an integer A, equal to the numRows.

Output Format

Return an array of array of integers, equal to pascal triangle.
Return an array of array of integers, equal to pascal triangle.

Example Input

A = 5
A = 5

Example Output

[
     [1],
     [1,1],
     [1,2,1],
     [1,3,3,1],
     [1,4,6,4,1]
]
[
     [1],
     [1,1],
     [1,2,1],
     [1,3,3,1],
     [1,4,6,4,1]
]

Solution

swift
import Foundation

class Solution {
	func solve(_ A: inout Int) -> [[Int]] {
		var B = [[Int]]()
		if A == 0 {
			return B
		}
		B.append([1])
		if A == 1 {
			return B
		}
		for i in 2...A {
			var C = [Int](repeating:1,count:i)
			var last = B.last!
			for j in 1..<(i-1) {
				C[j] = last[j-1] + last[j]
			}
			B.append(C)
		}
		return B	
	}
}
import Foundation

class Solution {
	func solve(_ A: inout Int) -> [[Int]] {
		var B = [[Int]]()
		if A == 0 {
			return B
		}
		B.append([1])
		if A == 1 {
			return B
		}
		for i in 2...A {
			var C = [Int](repeating:1,count:i)
			var last = B.last!
			for j in 1..<(i-1) {
				C[j] = last[j-1] + last[j]
			}
			B.append(C)
		}
		return B	
	}
}

References