题目
Given numRows, generate the first numRows of Pascal’s triangle.
For example, given numRows = 5,
Return
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
解题思路
对于每一行,先找到前一半的数,右半边的数可以根据左右对称得到
对于每一行,有如下规律,
- 对于第row行,有row+1个数
- 第1个数triangele[row][0]为1
- 第i个数(i < row/2 + 1), 等于triangle[row-1][i-1] + triangle[row-1][i]
- 剩余的row/2个数( row/2 < i < row ), 可以根据左边的数得到
代码
func generate(numRows int) [][]int {
var triangle [][]int
if 0 == numRows {
return triangle
}
triangle = append(triangle, []int{1})
if 1 == numRows {
return triangle
}
i := 1
for ; i < numRows; i++ {
var row []int
row = append(row, 1)
j := 1
for ; j < i/2 + 1; j++ {
tmp := triangle[i-1][j-1] + triangle[i-1][j]
row = append(row, tmp)
}
j = (i-1)/2
for ; j >=0; j-- {
row = append(row, row[j])
}
fmt.Printf("row:%+v", row)
triangle = append(triangle, row)
}
return triangle
}