美文网首页
leetcode:119. Pascal's Triangle

leetcode:119. Pascal's Triangle

作者: 唐僧取经 | 来源:发表于2018-08-19 13:53 被阅读0次

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

      本文链接:https://www.haomeiwen.com/subject/nkeciftx.html