题目表述
给定一个仅包含数字 2-9
的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例1
输入:digits = "23" 输出:["ad","ae","af","bd","be","bf","cd","ce","cf"]
示例2
输入:digits = "" 输出:[]
解题思路
利用 dfs思想
解题过程
class Solution {
public://将电话按键 对应的字符串一一映射出来string strA[10] = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};void Combination(string digits,int level,string Combinstr, vector<string>& v){ //递归返回的条件,层数完成后 返回if(level == digits.size()){v.push_back(Combinstr);return ;}int num = digits[level] - '0';string str = strA[num];//去映射关系中取出 对应字符串for(size_t i = 0;i<str.size();i++){Combination(digits,level+1,Combinstr + str[i],v);}}vector<string> letterCombinations(string digits) {//定义一个 接收字符串的 vector vector<string> v;if(digits.empty()) return v;Combination(digits,0,"",v);return v;}
};
递归演示