Learning GoLang: Generate a Pascal Triangle

in #bash5 years ago
Given an integer numRows, return the first numRows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:

Example 1:
Input: numRows = 5
Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]

Example 2:
Input: numRows = 1
Output: [[1]]

Generate a Pascal Triangle using GoLang


First declare a 2-dimension array with N rows, then fill each row, both ends are 1 and the internal value is equal to the sum of both numbers on its shoulder (Dynamic Programming Algorithm).

func generate(numRows int) [][]int {
    var res = make([][]int, numRows)
    for i := 0; i < numRows; i ++ {
        res[i] = make([]int, i + 1)
        res[i][0], res[i][i] = 1, 1
        for j := 1; j < i; j ++ {
            res[i][j] = res[i - 1][j] + res[i - 1][j - 1]
        }
    }
    return res
}

Another GoLang Implementation that appends row by row (beware that we need to deepcopy each row):

func generate(numRows int) [][]int {
    var res [][]int
    var cur []int    
    cur = append(cur, 1)
    for i := 0; i < numRows; i ++ {
        res = append(res, append([]int(nil), cur...))
        for j := i; j &gt; 0; j -- {
            cur[j] += cur[j - 1]
        }
        cur = append(cur, 1)
    }
    return res
}

Pascal Triangle Implementations:

Reposted to Blog

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Thank you for reading ^^^^^^^^^^^^^^^

NEW! Following my Trail (Upvote or/and Downvote)

Follow me for topics of Algorithms, Blockchain and Cloud.
I am @justyy - a Steem Witness
https://steemyy.com

My contributions

Delegation Service

Important Update of Delegation Service!

  • Delegate 1000 to justyy: Link
  • Delegate 5000 to justyy: Link
  • Delegate 10000 to justyy: Link

Support me

If you like my work, please:

  1. Delegate SP: https://steemyy.com/sp-delegate-form/?delegatee=justyy
  2. Vote @justyy as Witness: https://steemyy.com/witness-voting/?witness=justyy&action=approve
  3. Set @justyy as Proxy: https://steemyy.com/witness-voting/?witness=justyy&action=proxy
    Alternatively, you can vote witness or set proxy here: https://steemit.com/~witnesses

Sort:  

A greater move and job, you are have done so far sir.

that concept is really good, i love it.

hello sir @justyy, again you missed my post to upvote. I'm a delegator (66K SP) and I only post once in 24 hours.

here my post link : https://steemit.com/hive-129948/@rme/4fmfwq-grayscale-photography

UPDATE: got upvoted. the issue has been resolved. thanks :)

thank you very much sir :)

Coin Marketplace

STEEM 0.04
TRX 0.32
JST 0.082
BTC 59858.22
ETH 1573.84
USDT 1.00
SBD 0.42