For example, given numRows = 5,
Return
[ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ]
要小心指標的執行
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | /** * Return an array of arrays of size *returnSize. * The sizes of the arrays are returned as *columnSizes array. * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). */ int** generate(int numRows, int** columnSizes, int* returnSize) { if(numRows<=0)return NULL; *returnSize=numRows; columnSizes[0]=malloc(sizeof(int)*numRows); int ** ans=malloc(sizeof(int *)*numRows); for(int i=1;i<=numRows;i++){ int *level=malloc(sizeof(int)*i); columnSizes[0][i-1]=i; for(int j=0;j<i;j++){ if(j==0 || j==i-1)level[j]=1; else{ level[j]=ans[i-2][j-1]+ans[i-2][j]; } } ans[i-1]=level; } return ans; } |
沒有留言:
張貼留言