0118. Pascals Triangle

118. Pascal’s Triangle #

Problem #

Given a non-negative integer numRows, generate the first numRows of Pascal’s triangle.

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

Problem Summary #

Given a non-negative integer numRows, generate the first numRows rows of Pascal’s triangle. In Pascal’s triangle, each number is the sum of the numbers to its upper left and upper right.

Solution Approach #

  • Given an n, print the first n rows of Pascal’s triangle.
  • Easy problem. Just loop and print according to the generation rules of Pascal’s triangle.

Code #


package leetcode

func generate(numRows int) [][]int {
	result := [][]int{}
	for i := 0; i < numRows; i++ {
		row := []int{}
		for j := 0; j < i+1; j++ {
			if j == 0 || j == i {
				row = append(row, 1)
			} else if i > 1 {
				row = append(row, result[i-1][j-1]+result[i-1][j])
			}
		}
		result = append(result, row)
	}
	return result
}


Calendar Jun 25, 2026
Edit Edit this page
Total visits:   You are visitor No.
中文