-
Notifications
You must be signed in to change notification settings - Fork 0
/
6-pascalTriangle.swift
52 lines (40 loc) · 1013 Bytes
/
6-pascalTriangle.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
42
43
44
45
46
47
48
49
50
51
52
/*
THe objective is to reproduce the video that I watched yesterday from memory and make a
triangle pascal like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
where the node bellow is the sum of the two above.
*/
var numOfRows = 10
func solver(_ numOfRows: Int) -> [[Int]] {
var answer = [[Int]]()
for i in 1...numOfRows {
guard numOfRows > 0 else {
return [[]]
}
if i == 1 {
answer.append([1])
} else if i == 2 {
answer.append([1,1])
} else {
var nextRow = [Int]()
nextRow.append(1)
let prevRow = answer.last!
for j in 1..<prevRow.count {
var sum = 0
sum = prevRow[j] + prevRow[j-1]
nextRow.append(sum)
}
nextRow.append(1)
answer.append(nextRow)
}
}
return answer
}
let answer = solver(numOfRows)
for row in answer {
print(row)
}