18 line, pure C, 0 ms, iterative solution


  • 0
    H
    char** letterCombinations(char* digits, int* returnSize) {
        int i, len=strlen(digits);
        char **ret = malloc(sizeof(char*) * 1024);
        
        ret[0] = malloc(len+1);
        for(i=0; i<len; i++)
            ret[0][i]='a'+(digits[i]-'2')*3+(digits[i]>'7');
        ret[0][i] = '\0';
        
        int carry=(len==0), j;
        for(j=1; !carry; j++) {
            ret[j]=malloc(len+1);
            carry=1;
            for(i=0; i<len; i++) {
                ret[j][i]=ret[0][i]+(ret[j-1][i]-ret[0][i]+carry)%(3+(digits[i] == '7' || digits[i] == '9'));
                carry=(ret[0][i]+(ret[j-1][i]-ret[0][i]+carry))/(ret[0][i]+(3+(digits[i] == '7' || digits[i] == '9')));
            }
            ret[j][len]='\0';
        }
        
        *returnSize = j-1;
        return ret;
    }
    

Log in to reply
 

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