Why my code is wrong when digits="3".


  • 0
    B
       I can get the right answer{"d","e","f"} on my computer but the wrong answer {"","","","d","e","f"} when I submit the code to  leetcode, I don't know how to solve this!
    

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>

    void combineChar(int index, int len,char* digits);
    
    char** letterCombinations(char* digits, int* returnSize);
    
    int main()
    {
    	int *returnSize;
    	returnSize=(int *) malloc(sizeof(int));
    	char **result=letterCombinations("3",returnSize);
    	for (int i=0; i<*returnSize; i++)
    	{
    		printf("%s\n",result[i]);
    	}
    	printf("%d",*returnSize);
    	system("pause");
    }
    
    int total=64,size=0;
    char *buttons[8]={"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
    int buttonLen[8]={3,3,3,3,3,4,3,4};
    char *result;
    char** Combinations;
    
    
    char** letterCombinations(char* digits, int* returnSize) {
    	
    	int len=strlen(digits);
    	if (0==len)
    	{
    		*returnSize=0;
    		return NULL;
    	}
    	Combinations=(char**) malloc(sizeof(char*)*total);
    	result=(char*)malloc(sizeof(char)*len);
    	for (int i=0; i<total; i++) Combinations[i]=(char*)malloc(sizeof(char)*len);
    	combineChar(0,len,digits);
    	*returnSize=size;
    	//Combinations=(char**)realloc(Combinations,sizeof(char*)*size);
    	return Combinations;
    }
    
    void combineChar(int index, int len,char* digits)
    {
    	if (index==len)
    	{
    		for (int i=0; i<len; i++)
    			Combinations[size][i]=result[i];
    		Combinations[size][len]='\0';
    		size++;
    		if (size==total)
    		{
    			total<<=1;
    			Combinations=(char**)realloc(Combinations,sizeof(char*)*total);
    			for (int i=size; i<total; i++)
    				Combinations[i]=(char*)malloc(sizeof(char)*len);
    		}
    		return;
    	}
    	int digit=digits[index]-'2';
    	for (int i=0; i<buttonLen[digit]; i++)
    	{
    		result[index]=buttons[digit][i];
    		combineChar(index+1,len,digits);
    	}
    }

Log in to reply
 

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