forked from yuyongwei/Algorithms-In-Swift
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpascalsTriangle.swift
41 lines (35 loc) · 918 Bytes
/
pascalsTriangle.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
//
// pascalsTriangle.swift
//
//
// Created by Dong, Anyuan (133) on 2019/4/5.
//
import Foundation
/*
https://leetcode.com/problems/pascals-triangle/description/
*/
class Solution {
func generate(_ numRows: Int) -> [[Int]] {
guard numRows > 0 else {
return [[Int]]()
}
//init matrix
var pascal = Array(repeating: [Int](), count: numRows)
for i in 0 ... numRows - 1 {
if i == 0 {
pascal[i] = [1]
} else if i == 1 {
pascal[i] = [1, 1]
} else {
var temp = [Int]()
temp.append(1)
for j in 1 ... i - 1 {
temp.append(pascal[i - 1][j - 1] + pascal[i - 1][j])
}
temp.append(1)
pascal[i] = temp
}
}
return pascal
}
}