Pascal’s Triangle
Given a non-negative integer numRows, generate the first numRows of Pascal’s triangle.
In Pascal’s triangle, each number is the sum of the two numbers directly above it.
Example:
Input: 5
Output:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
C语言
/**
* 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) {
int **res=(int **)malloc(sizeof(int *)*numRows);
*columnSizes=(int *)malloc(sizeof(int)*numRows);
int i,j;
for(i=0;i<numRows;i++)
{
(*columnSizes)[i]=i+1;
res[i]=(int *)malloc(sizeof(int)*(i+1));
res[i][0]=1;
res[i][i]=1;
for(j=1;j<i;j++)
res[i][j]=res[i-1][j]+res[i-1][j-1];
}
return res;
}
Success
Details
Runtime: 4 ms, faster than 91.86% of C online submissions for Pascal’s Triangle.
Memory Usage: 7.2 MB, less than 8.00% of C online submissions for Pascal’s Triangle.
Next challenges:
python3中有个生成器yeild,yield是一个类似return的关键字,只不过,带有yield的函数,不再是一个普通的函数,而是一个生成器。在执行中,调用next()方法才开始真正执行
python3
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
res = [[1]]
for i in range(1,numRows):
print(res[-1]+[0],[0]+res[-1])
res.append(list(map(lambda x, y : x + y, res[-1]+[0], [0]+res[-1])))
return res[:numRows]
Success
Details
Runtime: 36 ms, faster than 77.44% of Python3 online submissions for Pascal’s Triangle.
Memory Usage: 13 MB, less than 5.83% of Python3 online submissions for Pascal’s Triangle.
Pascal’s Triangle II
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?
C语言
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int* getRow(int rowIndex, int* returnSize) {
if (rowIndex < 0)
return NULL;
int *res = (int*)malloc(sizeof(int) * (rowIndex + 1));
for (int row = 0; row <= rowIndex; row++)
for (int col = row; col >= 0; col--)
res[col] = (col == 0 || col == row) ? 1 : res[col] + res[col - 1];
*returnSize = rowIndex + 1;
return res;
}
Success
Details
Runtime: 4 ms, faster than 90.82% of C online submissions for Pascal’s Triangle II.
Memory Usage: 6.7 MB, less than 95.00% of C online submissions for Pascal’s Triangle II.
python3
class Solution:
def getRow(self, rowIndex: int) -> List[int]:
row = [1]
for i in range(1, rowIndex + 1):
row = [1] + [ row[x] + row[x - 1] for x in range(1, i)] + [1]
return row
Success
Details
Runtime: 40 ms, faster than 35.55% of Python3 online submissions for Pascal’s Triangle II.
Memory Usage: 13.2 MB, less than 5.12% of Python3 online submissions for Pascal’s Triangle II.