aboutsummaryrefslogtreecommitdiff
path: root/Computer_Science/leetcode/17-letter_combinations_of_a_phone_number.c
blob: eeabd21dc87132be31f7aa62ee6d7788c5d7f254 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
void helper(char **result, char *map[10], char *digits, char *tmp, int index, int *returnSize)
{
	char *p = map[*digits - '0'];
	for(; *p; ++p) {
		tmp[index] = *p;
		helper(result, map, digits + 1, tmp, index + 1, returnSize);
	}
	if(*digits == '\0') {
		*(result + *returnSize) = malloc(sizeof(char) * index + 1);
		for(int i = 0; i < index; i++) {
			*(*(result + *returnSize) + i) = tmp[i];
		}
		*(*(result + *returnSize) + index) = '\0';
		++*returnSize;
	}
}
char** letterCombinations(char* digits, int* returnSize) {
	int len = strlen(digits);
	int index = 0;
	char tmp[len + 1];
	char **result = malloc(sizeof(int *) * 100);
	char *map[10] = {
		" ", " ", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"
	};

	*returnSize = 0;

	if(len < 1)
		return result;

	while(*digits) {
		if(*digits >= '2' && *digits <= '9') {
			helper(result, map, digits, tmp, index, returnSize);
		} else {
			*returnSize = 0;
			break;
		}
		++digits;
	}

	return result;
}