119. Pascal's Triangle II

1.描述

Given an index k, return the kth row of the Pascal's triangle.

For example, given k = 3,
Return [1,3,3,1].

Note:
Could you optimize your algorithm to use only O(k) extra space?

2.分析

3.代码

/**
 * 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;
    *returnSize = rowIndex + 1;
    int* row = (int*)malloc(sizeof(int) * (*returnSize));
    for (unsigned int i = 0; i< *returnSize; ++i) 
        row[i] = 1;
    for (unsigned int i = 1; i<= rowIndex; ++i) {
        int tmp = row[0];
        for (unsigned int j = 1; j < i; ++j) {
            int tmp2 = row[j];
            row[j] = tmp + tmp2;
            tmp = tmp2;
        }
    }
    return row;
}

你可能感兴趣的:(119. Pascal's Triangle II)