LeetCode1118 杨辉三角

26 阅读1分钟

leetcode.cn/problems/pa…

image.png

解法一:迭代法

func generate(numRows int) [][]int {
    res := make([][]int, 0)
    if numRows == 0{
        return res
    }
    // 初始第一行
    res = append(res, []int{1})
    // 从第二行开始逐层生成
    for i:=1; i<numRows; i++{ // 假设行号从0开始
        prevRow := res[len(res)-1]
        curRow := generateNextRow(prevRow)
        res = append(res, curRow)
    }
    return res
}

func generateNextRow(prevRow []int) []int{
    // 每一行的左右两端都是1
    curRow := []int{1}
    for i := 0; i<len(prevRow)-1; i++{ // 处理中间的值
        curRow = append(curRow, prevRow[i]+prevRow[i+1])
    }
    curRow = append(curRow, 1)
    return curRow
}

解法二:递归

func generate(numRows int) [][]int {
    return generateRecursive(numRows)
}

func generateRecursive(numRows int) [][]int {
    // 递归的 base case
    if numRows == 1 {
        triangle := [][]int{}
        // 先把第一层装进去作为 base case
        firstRow := []int{1}
        triangle = append(triangle, firstRow)
        return triangle
    }

    // 先递归生成高度为 numRows - 1 的杨辉三角
    triangle := generateRecursive(numRows - 1)

    // 根据最底层元素生成一行新元素
    bottomRow := triangle[len(triangle)-1]
    newRow := []int{1}
    for i := 0; i < len(bottomRow)-1; i++ {
        newRow = append(newRow, bottomRow[i]+bottomRow[i+1])
    }
    newRow = append(newRow, 1)
    // 把新的一行放到杨辉三角底部
    triangle = append(triangle, newRow)

    return triangle
}