原因:多位数组遍历会产生多层循环,循环中再嵌套逻辑会使得函数变得庞大,难以维护。
解决方法:内层的for循环包装成函数。如下:
118. Pascal's Triangle
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 {
res := [][]int{}
if numRows == 0 {
return res
}
res = append(res,[]int{1})
for i:=1; i<numRows; i++ {
res = append(res,genNext(res[i-1]))
}
return res
}
func genNext(p []int) []int {
r := make([]int,1,len(p)+1)
r = append(r,p...)
for i:=0; i<len(r)-1; i++ {
r[i] = r[i] + r[i+1]
}
return r
}