/**
* Note: The returned array must be malloced, assume caller calls free().
*/
/*
回溯法框架解题:
result = []
def backtrack(路径, 选择列表):
if 满足结束条件:
result.add(路径)
return
for 选择 in 选择列表:
做选择
backtrack(路径, 选择列表)
撤销选择
*/
#define MAX_LEN (3 * 3 * 3 * 3 * 3 * 4 * 3 * 4 + 1) // 可能的组合个数
char *digitsToStr[10] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
void letterCombinationsSub(char *digits, char **result, int *returnSize, char *str, int index) {
char *p;
int digitssNum = strlen(digits);
if (digitssNum == index) {
result[*returnSize] = (char *)calloc(strlen(str) + 1, sizeof(char));
strcpy(result[*returnSize], str);
(*returnSize)++;
return;
}
for (int i = 0; i < 4; i++) {
char c = digitsToStr[digits[index] - '0'][i];
if (c) {
str[index] = c;
letterCombinationsSub(digits, result, returnSize, str, index + 1);
str[index] = '\0';
}
}
return;
}
char ** letterCombinations(char * digits, int* returnSize){
if (digits == NULL) return NULL;
*returnSize = 0;
if (strlen(digits) == 0) return NULL;
char **result = (char **)malloc(sizeof(char *) * MAX_LEN);
char *str = calloc(10, sizeof (char)); // 返回结果的每个字符串的最大长度为9
letterCombinationsSub(digits, result, returnSize, str, 0);
return result;
}
leetcode(回溯法):17. 电话号码的字母组合
最新推荐文章于 2022-07-16 10:13:23 发布