Clean 3ms c solution


  • 0
    T

    It seems everyone is posting C++ solution. though the question is about boundary checking and array manipulation, memory allocation for c code might be tricky for beginners. Here I give a clean c solution
    you can NOT allocate extra space like the following code for dealing with boundary check. because free() might crash

    // you can fool solution check but free will crash
    arr[i-1] = malloc((i+2) * sizeof(int)); arr[i-1]+1;
    arr[i-1][-1] = 0;
    arr[i-1][i] = 0;
    
    int** generate(int numRows, int** columnSizes) {
        int **arr = malloc(numRows*sizeof(int *));
        *columnSizes = malloc(numRows * sizeof(int));
        for(int i=1; i<=numRows; i++) {
            arr[i-1] = malloc(i * sizeof(int));
            (*columnSizes)[i-1] = i;
            if(i>1)
                for(int j=0; j<i; j++) 
                    arr[i-1][j] = (j-1>=0?arr[i-1-1][j-1]:0)+(j<i-1?arr[i-1-1][j]:0);
            else 
                arr[0][0] = 1;
        }
        return arr;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.