一.问题描述
Given a digit string, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below.
二.我的解题思路
这道题没有什么特殊的技巧,其实就是简单的遍历问题。那么问题就是漂亮的写出遍历的程序,而不是一堆for循环的堆积,这就需要用到回溯的算法思想了。这道题的解空间是子集树,可以采用递归的形式完成回溯。回溯算法思想的详细介绍可以参加《计算机算法设计与分析 王晓东》P114。测试通过的程序如下:
class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string> res={};
if(digits.length()==0)
return res;
string record(digits);
int depth=digits.length();int i=0;
back_track(digits,i,depth,record,res);
return res;
}
private:
string map[8]={"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
void back_track(string digit,int i,int depth,string& record,vector<string>& res){
if(i>=depth) res.push_back(record);
else{
int idx=digit[i]-'2';
string curr(map[idx]);
for(int k=0;k<curr.length();k++){
record[i]=curr[k];
back_track(digit,i+1,depth,record,res);
}
}
}
};