leetcode:119. Pascal's Triangle II

119. Pascal's Triangle II

Description

Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.

Note that the row index starts from 0.

In Pascal's triangle, each number is the sum of the two numbers directly above it.

Example:

Input: 3
Output: [1,3,3,1]
Follow up:

Could you optimize your algorithm to use only O(k) extra space?

Answer


package main

import "fmt"

func getRow(rowIndex int) []int {
    if rowIndex < 0 {
        return []int{}
    }

    ret := [][]int{[]int{1}}
    if rowIndex == 0 {
        return ret[0]
    }

    for i := 1; i <= rowIndex; i++ {
        temp := make([]int, i+1)
        temp[0] = 1
        for j := 1; j < i; j++ {
            temp[j] = ret[i-1][j-1] + ret[i-1][j]
        }

        temp[i] = 1

        ret = append(ret, temp)
    }
    return ret[rowIndex]

}

func main() {
    fmt.Println(getRow(3))
}


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