在这里插入图片描述
回溯实现,但是需要练习一下C语言写法:
cpp
class Solution {
private:
string phone[8]={
"abc",
"def",
"ghi",
"jkl",
"mno",
"pqrs",
"tuv",
"wxyz"
};
vector<string>result;
string path;
void backtracking(string s,int startindex)
{
if(startindex==s.size()){
result.push_back(path);
return;
}
int index=s[startindex]-'2';
for(int j=0;j<phone[index].size();j++){
path.push_back(phone[index][j]);
backtracking(s,startindex+1);
path.pop_back();
}
}
public:
vector<string> letterCombinations(string digits) {
if(digits.size()==0)
return result;
backtracking(digits,0);
return result;
}
};
C:
c
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
char** result;
char* path;
int resultTop;
int pathTop;
const char* letter[] = {
"",
"",
"abc",
"def",
"ghi",
"jkl",
"mno",
"pqrs",
"tuv",
"wxyz"
};
//回溯
void backtracking(int size, char* digits,int startindex)
{
if(size==0)
return;
if (pathTop == size)//当遍历完所有数字(遍历到数的空节点了),则存下此次遍历的结果
{
char* temp = (char*)malloc(sizeof(int) * size);
for (int i = 0;i < size;i++)
{
temp[i] = path[i];
}
temp[size] = '\0';//字符串结尾
result[resultTop++] = temp;
return;
}
//将字符数字转换为真的数字
int digit = digits[startindex] - '0';
for (int j = 0;j < strlen(letter[digit]);j++)
{
path[pathTop++] = letter[digit][j];//处理当前数字对应的字符串中的字母
backtracking(size,digits,startindex + 1);//递归
pathTop--;//回溯
}
}
char** letterCombinations(char* digits, int* returnSize) {
int size = strlen(digits);
result = (char**)malloc(sizeof(int*) * 1000);
path = (char*)malloc(sizeof(int) * size);
resultTop = pathTop = 0;
backtracking(size,digits,0);
*returnSize = resultTop;
return result;
}