描述
Write a function that when given a number >= 0, returns an Array of ascending length subarrays.
pyramid(0) => [ ]
pyramid(1) => [ [1] ]
pyramid(2) => [ [1], [1, 1] ]
pyramid(3) => [ [1], [1, 1], [1, 1, 1] ]
Note: the subarrays should be filled with 1s
分析
方法1:递推
方法2:递归
实现
方法1:
func Pyramid(n int) [][]int {
ssi, si := [][]int{}, []int{}
for i := 0; i < n; i++ {
si = append(si, 1)
ssi = append(ssi, si) // NOTE
}
return ssi
}
注:每次循环slice si内容都会变化,但由于之前append到ssi的si已被复制,而非引用,故当前si变化并不会影响之前已append到ssi的si的内容。
方法2:
func Pyramid(n int) [][]int {
if n == 0 { return [][]int{} }
si := []int{}
for i := 0; i < n; i++ { si = append(si, 1) }
return append(Pyramid(n - 1), si)
}