What's wrong with my c solution?


  • 0
    K
    char* getPermutation(int n, int k) {
        int getMul(int n);
        int* resultInt = (int*)malloc(n * sizeof(int));
        char* resultChar = (char*)malloc(n * sizeof(char));
        int originalN = n;
        //initialize
        for(int i = 0; i < originalN; i++)
        {
            resultInt[i] = i+1;
        }
        
        int startIndex;
        int itemIndex;
        int temp;
        int mul;
        
        while(k != 1)
        {
            mul = getMul(n-1);
            startIndex = originalN - n;
            itemIndex = (k-1) / mul;
            temp = resultInt[startIndex+itemIndex];
            for(int i = itemIndex+startIndex; i > startIndex; i--)
            {
                resultInt[i] = resultInt[i-1];
            }
            resultInt[startIndex] = temp;
            k = k - itemIndex*mul;
            n--;
        }
        
        for(int i = 0; i < originalN; i++)
        {
            resultChar[i] = (char) (resultInt[i] - 0 + '0');
        }
        
        free(resultInt);
        
        return resultChar;
        
    }
    
    int getMul(int n)
    {
        if((n == 0) || (n == 1))
        {
            return 1;
        }else
        {
            return n*getMul(n-1);
        }
    }
    

    result


  • 0
    K
    int* resultInt = (int*)malloc(n * sizeof(int));
    char* resultChar = (char*)malloc(n * sizeof(char));
    

    I changed the code above to

    int* resultInt = (int*)malloc(n * sizeof(int*));
    char* resultChar = (char*)malloc(n * sizeof(char*));
    

    and it is accepted.


Log in to reply
 

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