Skip to content

119. Pascal's Triangle II

https://leetcode.com/problems/pascals-triangle-ii/

js
/**
 * @param {number} rowIndex
 * @return {number[]}
 */
function getRow(rowIndex) {
  let prev = []
  let result = [1]

  for (let i = 1; i <= rowIndex; i++) {
    prev = result
    result = []

    for (let j = 0; j < i + 1; j++) {
      if (j === 0 || j === i) {
        result.push(1)
      } else {
        result.push(prev[j - 1] + prev[j])
      }
    }
  }

  return result
}
py
class Solution(object):

    def getRow(self, rowIndex):
        """
        :type rowIndex: int
        :rtype: List[int]
        """
        prev, result = [], [1]

        for i in range(1, rowIndex + 1):
            prev, result = result, []
            for j in range(i + 1):
                if j == 0 or j == i:
                    result.append(1)
                else:
                    result.append(prev[j - 1] + prev[j])

        return result
go
func getRow(rowIndex int) []int {
	prev := []int{}
	result := []int{1}

	for i := 1; i <= rowIndex; i++ {
		prev = result
		result = []int{}

		for j := 0; j < i+1; j++ {
			if j == 0 || j == i {
				result = append(result, 1)
			} else {
				result = append(result, prev[j-1]+prev[j])
			}
		}
	}

	return result
}