题目
生成杨辉三角
解析
- 每一层宽度 + 1
- 每一层首尾填充 1
- 每一层需要填充的个数为 n-2
- 值计算为 lv[n][i] = lv[n-1][n-1] + lv[n]
- 对称点计算 lv[n][n-i] = lv[n][i]
伪代码
代码
func generate(numRows int) [][]int {
triangle := make([][]int, numRows)
triangle[0] = []int{1}
for i:=1; i<numRows; i++ {
triangle[i] = make([]int, i+1)
for k:=1; k<=i/2; k++ {
triangle[i][k] = triangle[i-1][k-1] + triangle[i-1][k]
triangle[i][i-k] = triangle[i][k]
}
triangle[i][0] = 1
triangle[i][i] = 1
}
return triangle
}
image.png
网友评论