leetcode:118. Pascal's Triangle

118. Pascal's Triangle

Description

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]
]

Answer

package main

import "fmt"

func generate(numRows int) [][]int {
    //为0的时候,返回空
    if numRows == 0 {
        return [][]int{}
    }
    //返回的切片,先放一个切片
    ret := [][]int{[]int{1}}
    //创建第一个数
    if numRows == 1 {
        return ret
    }
    for i := 1; i < numRows; i++ {
        //定义临时的切片,代表每一行
        tmp := make([]int, i+1)
        tmp[0] = 1
        for j := 1; j < i; j++ {
            //下面这一行等于上面两个的和
            tmp[j] = ret[i-1][j-1] + ret[i-1][j]
        }
        tmp[i] = 1
        ret = append(ret, tmp)
    }
    return ret
}

func main() {
    fmt.Println(generate(5))
}


你可能感兴趣的:(leetcode:118. Pascal's Triangle)