题目:
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?
思路:
因为每一层的数都是对称的,所以只需要计算每一层的前半部分的值,后半部拷贝就可以了。res[i] = res`[i - 1] + res`[i](res`代表原数组,res代表更新后的数组),tmp代表res`[i - 1],tmp2代表 res`[i]。
代码:
int* getRow(int rowIndex, int* returnSize) { if(rowIndex < 0) return NULL; ++rowIndex; int *res = (int*)malloc(sizeof(int) * rowIndex); res[0] = 1; int count = rowIndex; while(--count){ int real_index = rowIndex - count + 1; int half = real_index / 2; if(real_index % 2 == 0){ half--; } int tmp = res[0]; int i = 1; for(; i <= half; i++){ int tmp2 = res[i]; res[i] = tmp + tmp2; tmp = tmp2; } if(real_index % 2){ i -= 2; } else { --i; } for(int j = half + 1; j < real_index; j++){ res[j] = res[i--]; } } *returnSize = rowIndex; return res; }
LeetCode OJ:Pascal's Triangle II
时间: 2024-10-06 05:26:48