题目描述
Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it.
Example:
Input: 5
Output: [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ]
解题思路
杨辉三角
示例代码
func generate(_ numRows: Int) -> [[Int]] {
if numRows == 0 {
return []
}
var result: [[Int]] = []
for i in 1...numRows {
var temp: [Int] = Array.init(repeating: 0, count: i)
for j in 0..<i {
if j == 0 || j == (i-1) {
temp[j] = 1
}else {
let lastLine = result[i-2]
temp[j] = lastLine[j-1] + lastLine[j]
}
}
result.append(temp)
}
return result
}