My code with C 1ms


  • 0
    E
    int uniquePaths(int m, int n) {
        int res = 0;
        int i, j;
        int **tmp = (int **)malloc(sizeof(int *) * m);
        for(int i = 0; i < m; ++i) {
            tmp[i] = (int *)malloc(sizeof(int) * n);
        }
        
        tmp[0][0] = 1;
        //tmp[0][1] = tmp[1][0] = 1;
        for(i = 1; i < m; ++i)
            tmp[i][0] = 1;
        for(i = 1; i < n; ++i)
            tmp[0][i] = 1;
    
        
        for(int i = 1; i < m; ++i)
            for(int j = 1; j < n; ++j)
                tmp[i][j] = tmp[i][j - 1] + tmp[i - 1][j];
        res = tmp[m - 1][n - 1];
        for(int i = 0; i < m; ++i)
            free(tmp[i]);
        free(tmp);
        return res;
    }

  • 0
    9

    your code tmp[i] = (int *)malloc(sizeof(int *) * n);

    maybe should be correct as: tmp[i] = (int *)malloc(sizeof(int) * n);


  • 0
    E

    the tmp[i] is a array of which elements are pointers, so it should be sizeof(int *)
    but on most implementation the size of an int is just as that of a pointer, a coincidence


  • 0
    9

    I think maybe code should write as follows:

    int **tmp = (int **)malloc(sizeof(int *) * m);
    for(int i = 0; i < m; ++i) {
    tmp[i] = (int *)malloc(sizeof(int) * n);
    }

    since tmp[i] is just a pointer, it point an address of some array containing n int elements.

    your code can AC because the value of sizeof(int **), sizeof(int *) and sizeof(int) are equal, a coincidence.


  • 0
    9

    I think maybe code should write as follows:

    int **tmp = (int **)malloc(sizeof(int *) * m);
    for(int i = 0; i < m; ++i) {
        tmp[i] = (int *)malloc(sizeof(int) * n);
    }
    

    since tmp[i] is just a pointer, it point an address of some array containing n int elements.

    your code can AC because the value of sizeof(int **), sizeof(int *) and sizeof(int) are equal, a coincidence.


  • 0
    9

    the tmp[i] is not a array, it just is a pointer.


  • 0
    E

    yeah, you are right, i made a mistake
    thanks for your correction
    have a good day


Log in to reply
 

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