leetcode119:杨辉三角 II(pascals-triangle-ii)
carloscn opened this issue · comments
Carlos Wei (Haochen) commented
问题描述:
给定一个非负索引 rowIndex,返回「杨辉三角」的第 rowIndex 行。
示例 1:
输入: rowIndex = 3
输出: [1,3,3,1]
示例 2:
输入: rowIndex = 0
输出: [1]
示例 3:
输入: rowIndex = 1
输出: [1,1]
提示:
0 <= rowIndex <= 33
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/pascals-triangle-ii
Carlos Wei (Haochen) commented
分析:
和上一个问题一样leetcode118:杨辉三角(pascals-triangle) 只不过我们不需要保存这么多的杨辉三角数据。但是三角形之间有依赖关系,因此我们要备份上一个三角形,用完之后就free掉。
static int32_t gen_pascals_triangle(int64_t **return_array, size_t *n)
{
int32_t ret = 0;
size_t i = 0, j = 0;
int64_t *new_array = NULL;
int64_t *last_array = NULL;
size_t depth = 0;
UTILS_CHECK_PTR(n);
if (*n > 33 || 0 == *n) {
ret = -1;
LOG("input error n is over the 33, or is 0.\n");
goto finish;
}
UTILS_CHECK_PTR(return_array);
for (i = 0; i < *n; i ++) {
last_array = new_array;
new_array = NULL;
new_array = (int64_t*)malloc(sizeof(int64_t) * (i + 1));
UTILS_CHECK_PTR(new_array);
new_array[0] = new_array[i] = 1;
depth ++;
if (i < 2) {
last_array = new_array;
continue;
}
for (j = 1; j <= depth - 2; j ++)
new_array[j] = last_array[j] + last_array[j - 1];
if (NULL != last_array)
free(last_array);
}
*return_array = new_array;
*n = depth;
finish:
return ret;
}