给定一个非负索引 rowIndex
,返回「杨辉三角」的第 rowIndex
行。
在「杨辉三角」中,每个数是它左上方和右上方的数的和。
来源:力扣(LeetCode)
线性递推
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int
* getRow(int rowIndex, int* returnSize)
{
*returnSize = rowIndex + 1;
int *ans = malloc (sizeof (int) * (*returnSize));
ans[0] = 1;
int i;
for (i = 1; i <= rowIndex; i ++)
{
ans[i] = 1LL * ans[i - 1] * (rowIndex - i + 1) / i;
}
return ans;
}
暴力法
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int
* getRow(int rowIndex, int* returnSize)
{
int* result = malloc (sizeof (int) * (rowIndex + 1));
*returnSize = rowIndex + 1;
for(int i = 0; i <= rowIndex; i ++)
{
for(int j = i - 1; j > 0; j --)
{
result[j] = result[j] + result[j - 1];
}
result[i] = 1;
}
return result;
}