S2 icon indicating copy to clipboard operation
S2 copied to clipboard

0118. Pascals Triangle | LeetCode Cookbook

Open halfrost opened this issue 4 years ago • 4 comments

https://books.halfrost.com/leetcode/ChapterFour/0100~0199/0118.Pascals-Triangle/

halfrost avatar Feb 16 '21 05:02 halfrost

从空slice开始append会有因为capacity被超过导致多余的allocation以及copy。更简洁的做法是直接按照row size来allocate:

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

hanlins avatar Jun 25 '21 04:06 hanlins

@hanlins 还是你写代码更细心啊。你说的是对的👍🏻。关于 row 和 col 在 csapp 上和一些面试题上经常出现。

halfrost avatar Jun 26 '21 08:06 halfrost

def generation(self,num):
    res = [[1 for j in range(i)] for i in range(1,num + 1)]
    for i in range(2,num):
        for j in range(1,i):
            res[i][j] = res[i-1][j-1] + res[i-1][j]
    return res

claraoswald1 avatar Jan 22 '22 02:01 claraoswald1

ret := make([][]int, numRows)
for i := 0; i < numRows; i++ {
	ret[i] = make([]int, i+1)
	for j := 0; j <= i; j++ {
		if i == j || j < 1 {
			ret[i][j] = 1
			continue
		}
		ret[i][j] = ret[i-1][j] + ret[i-1][j-1]
	}
}
return ret

ZGGSONG avatar Aug 04 '22 07:08 ZGGSONG