本文主要是介绍刷题之电话号码的字母组合(leetcode),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
电话号码的字母组合
在这里插入图片描述
回溯实现,但是需要练习一下C语言写法:
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:
/*** 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;
}
这篇关于刷题之电话号码的字母组合(leetcode)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!