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?
主要找到第K行数据的规律,
杨辉三角形,又称贾宪三角形,帕斯卡三角形,是二项式系数在三角形中的一种几何排列.杨辉三角形同时对应于二项式定理的系数.n次的二项式系数对应杨辉三角形的n + 1行.例如在中,2次的二项式正好对应杨辉三角形第3行系数 1 2 1.
/** * Return an array of size *returnSize. * Note: The returned array must be malloced, assume caller calls free(). */ int* getRow(int rowIndex, int* returnSize) { if(!returnSize || rowIndex < 0) { return NULL; } int i = 0; int *columnArray = (int *)malloc(sizeof(int)*(rowIndex+1)); if(0 == rowIndex) { columnArray[0] =1; *returnSize = 1; return columnArray; } columnArray[0] =1; columnArray[1] = rowIndex; columnArray[rowIndex] = 1;/*最后一行*/ for(i=2;i<rowIndex;i++) { columnArray[i] = (double)columnArray[i-1]*(rowIndex-(i-1))/i; } *returnSize = rowIndex+1; return columnArray; }
另外一个超时版本
int* getRow(int rowIndex, int* returnSize) { if(!returnSize || rowIndex < 0) { return NULL; } int i,j = 0; int *columnArray = (int *)malloc(sizeof(int)*(rowIndex+1)); if(0 == rowIndex) { columnArray[0] =1; *returnSize = 1; return columnArray; } int **AllColumnArray = (int **)malloc(sizeof(int)*(rowIndex+1)); for(i=0;i<=rowIndex;i++) { /*i:当前行*/ AllColumnArray[i] = (int *)malloc(sizeof(int)*(i+1)); AllColumnArray[i][0] = 1; /*第一个数为1*/ for(j=1;j<i;j++) { /*j:当前的列数*/ AllColumnArray[i][j] = AllColumnArray[i-1][j-1]+AllColumnArray[i-1][j]; } if(i>=1) { AllColumnArray[i][j] = 1;/*当前最后一个数也为1*/ free(AllColumnArray[i-1]); /*及时释放回系统*/ AllColumnArray[i-1] = NULL; } AllColumnArray[i][j] = 1;/*当前最后一个数也为1*/ } /*赋值给输出数组*/ for(j=0;j<=rowIndex;j++) { /*i:当前行*/ columnArray[j] = AllColumnArray[i-1][j]; } free(AllColumnArray[i-1]); AllColumnArray[i-1] = NULL; free(AllColumnArray); AllColumnArray = NULL; *returnSize = rowIndex+1; return columnArray; }