代码实现:
package main
import "fmt"
func main() {
//arr := generate(0)
res := getRow(3)
fmt.Println(res)
}
/**
* @Description: 杨辉三角 I 类似动态规划
*
* @Date:
* @Author: fuGuoWen
* @Return
* @Throws
*/
func generate(numRows int) [][]int {
/** 创建二维数组 */
res := make([][]int, numRows)
if numRows == 0 {
return res
}
res[0] = []int{1}
for i := 1; i < numRows; i++ {
/** 创建一维数组 */
res[i] = make([]int, i+1)
res[i][0] = 1
res[i][i] = 1
for j := 1; j < i; j++ {
/** 下面的元素等于上面元素的和 */
res[i][j] = res[i-1][j-1] + res[i-1][j]
}
}
return res
}
/**
* @Description: 杨辉三角 II
*
* @Date:
* @Author: fuGuoWen
* @Return
* @Throws
*/
func getRow(rowIndex int) []int {
//创建切片
res := make([]int, rowIndex+1)
res[0] = 1
for i := 1; i <= rowIndex; i++ {
//从后向前迭代元素,如果是从前向后会出现数据覆盖,故从后向前迭代
for j := i; j > 0; j-- {
res[j] = res[j-1] + res[j]
}
}
return res
}