1. 程式人生 > >LeetCode 楊輝三角 題目解答

LeetCode 楊輝三角 題目解答

/**
 * Return an array of arrays.
 * 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) {
    
    printf("row : %d\n",numRows);
    int row = numRows;
    
    int** p = NULL;

    if(numRows == 0)
    {
        *columnSizes = NULL;
        return p;
    }
    p = (int**)malloc(sizeof(int*)*row);
    *columnSizes = (int*)malloc(sizeof(int)*row);
    
    for(int i = 0;i<row;i++)
    {
        int j = i+1;
        p[i] = (int*)malloc(sizeof(int)*j);
       // columnSizes[i]=(int*)malloc(sizeof(int));
        (*columnSizes)[i] = j;
        if(i == 0)//first row
        {
            p[i][0] = 1;
            printf("%d \n",p[i][0]);
        }
        else
        {
           // printf("colsize :%d\n",j);
            for(int k = 0;k<j;k++)
            {
                if(k == 0||k == j-1)
                {
                     p[i][k] = 1;
                    printf("%d \t",p[i][k]);
                    if(k == j-1)
                    {
                         printf("\n");
                    }
                }
                else
                {
                    p[i][k] = p[i-1][k-1]+p[i-1][k];
                    printf("%d \t",p[i][k]);
                }
            }
        }
    }
   
    return p;  
  }

 

思考:

numRows:輸入的行數

columnSize:二維陣列用於存放 每一行元素的個數(真是坑,如果這個值沒做好,那麼提交是讀不出每行的元素的)

*columnSizes = (int*)malloc(sizeof(int)*row);

(*columnSizes)[i] = j; 記錄每一行的 元素個數=行數+1

函式裡:

1.注意極限值:例如 輸入 row = 0;則返回NULL指標

2.邊界元素均為 1