python import this翻译_python3 import tableetcode118题 题解 翻译 C语言版 Python版

118. Pascal's Triangle

Given numRows, generate the first numRows of Pascal's triangle.

For example, given numRows = 5,

Return

[

[1],

[1,1],

[1,2,1],

[1,3,3,1],

[1,4,6,4,1]

]118.帕斯卡三角形

给定一个行数numRows,生成一个对应的帕斯卡三角形

举个例子,给定numRows=5,

返回

[

[1],

[1,1],

[1,2,1],

[1,3,3,1],

[1,4,6,4,1]

]思路:逐行分配内存空间,对第i行来说首尾填1,然后中间的各数由上一行对应位置的两数相加即可得到。整个过程较为简单。需要注意的是c语言版中函数提供的参数的理解。函数头如下:

int** generate(int numRows, int** columnSizes)

最后返回一个二级指针表示存储的三角形,这里可以一次性分配全部的内存,也可以逐行分配使得内存不连在一起。由于每行的长度是事先不确定的,所以需要我们来计算并返回,这就体现在columnSizes中。本来各行长度连起来应该是一个一维数组,也就是说在函数中我们只需要定义一个int*型变量并malloc这么一个一维数组,即可记录各行的长度。但是如果我们要通过指针的方式将其地址传出函数,那么就要再来一层指针,也就是变成了二级指针int**。具体使用中一直使其以*columnSizes的形式出现即可。

《python3 import tableetcode118题 题解 翻译 C语言版 Python版》总结了关于学习电脑教程,对于我们来www.002pc.com确实能学到不少知识。

/**

* Return an array of arrays.

* The sizes of the arrays are returned as *columnSizes array.

* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().

*/

int** generate(int numRows, int** columnSizes) {

*columnSizes = (int*)malloc(sizeof(int)*numRows);

int** triangle = (int**)malloc(sizeof(int*)*numRows);

for (int i = 0; i < numRows; i++){

(*columnSizes)[i] = i + 1;

triangle[i] = (int*)malloc(sizeof(int)*(i+1));

triangle[i][0] = triangle[i][i] = 1;

for (int j = 1; j < i; j++){

triangle[i][j] = triangle[i-1][j-1] + triangle[i-1][j];

}

}

return triangle;

}class Solution(object):

def generate(self, numRows):

"""

:type numRows: int

:rtype: List[List[int]]

"""

triangle = []

for i in range(numRows):

row = [1]

if i == 0:

triangle.append(row)

continue

for j in range(1, i):

num = triangle[i-1][j-1] + triangle[i-1][j]

row.append(num)

row.append(1)

triangle.append(row)

return triangle

更多:python3 import tableetcode118题 题解 翻译 C语言版 Python版

https://www.002pc.comhttps://www.002pc.com/python/4897.html

你可能感兴趣的题解,Python,leetcode118,C语言,翻译

No alive nodes found in your cluster

0踩

0 赞

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值