给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行。
在杨辉三角中,每个数是它左上方和右上方的数的和。
示例:
输入: 3
输出: [1,3,3,1]
C语言版:
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int* getRow(int rowIndex, int* returnSize) {
int i, j;
int** array = (int **)malloc((rowIndex + 1) * sizeof(int *));
*returnSize = rowIndex + 1;
for(i = 0; i < rowIndex + 1; i++){
array[i] = (int *)malloc((i + 1) * sizeof(int));
for(j = 0; j < i + 1; j++){
if((j == 0) || (j == i))
array[i][j] = 1;
else
array[i][j] = array[i - 1][j - 1] + array[i - 1][j];
}
}
return array[rowIndex];
}
Python版:
class Solution:
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
result = []
for i in range(rowIndex + 1):
temp = []
for j in range(i + 1):
if j== 0:
temp.append(1)
elif j == i:
temp.append(1)
else:
temp.append(result[i - 1][j - 1] + result[i - 1][j])
result.append(temp)
return result[rowIndex][:]