118.杨辉三角

题目描述

给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。

UUA7VA.gif

在杨辉三角中,每个数是它左上方和右上方的数的和。

示例:

1
2
3
4
5
6
7
8
9
输入: 5
输出:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]

题解

思路

wengcanzi

C:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* Return an array of arrays of size *returnSize.
* The sizes of the arrays are returned as *returnColumnSizes array.
* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
*/
int** generate(int numRows, int* returnSize, int** returnColumnSizes){
*returnSize = numRows;
int** res = (int**)malloc(sizeof(int*)*numRows);

int i;
for(i = 0; i < numRows; i++){
(*returnColumnSizes)[i] = i+1;//returnColumnSizes储存杨辉三角每一行元素的个数
res[i] = (int*)malloc(sizeof(int)*(i+1));
res[i][0] = 1;
res[i][i] = 1;
int j;
for(j = 1; j < i; j++){
res[i][j] = res[i-1][j] + res[i-1][j-1];
}
}
return res;
}

思路

取巧解法:错一位再逐个相加

Python:

1
2
3
4
5
6
7
8
9
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
if numRows == 0:
return []
res = [[1]]
while len(res) < numRows:
newRow = [a+b for a, b in zip([0]+res[-1], res[-1]+[0])]
res.append(newRow)
return res