Given an index k, return the kth row of the Pascal's triangle.
- Could you optimize your algorithm to use only O(k) extra space?
For example, given k = 3, Return [1,3,3,1].
C Solution:
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int* getRow(int rowIndex, int* returnSize) {
int *res = malloc((rowIndex + 1) * sizeof(int));
*returnSize = rowIndex + 1;
int i;
for (i = 0; i < rowIndex + 1; i++) {
res[i] = 1;
int j;
for (j = i - 1; j > 0; j--) {
res[j] += res[j - 1];
}
}
return res;
}
Python Solution:
class Solution(object):
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
res = [0] * (rowIndex + 1)
res[0] = 1
for i in range(1, rowIndex + 1):
for j in range(1, i + 1):
j = i + 1 - j
res[j] += res[j - 1]
return res
Summary:
- nothing to say
LeetCode: 119. Pascal's Triangle II





近期评论