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.
Input:Digit string "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
The idea is to use recursion. DFS slove it.
Java
public class LetterCombinationPhoneNum {
ArrayList<String> res;
StringBuffer seq;
public void getletterComba(String digits, int level, String[] trans){
if(level == digits.length()){
res.add(seq.toString());
return;
}
int digit = digits.charAt(level)-48;
for(int i=0;i<trans[digit].length();i++){
seq.append(trans[digit].charAt(i));
getletterComba(digits, level+1, trans);
seq.deleteCharAt(level);
}
}
public List<String> letterCombinations(String digits) {
res = new ArrayList<>();
seq = new StringBuffer();
String []trans = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
getletterComba(digits, 0, trans);
return res;
}
}
c++
public:
void getLetterCombination(string &seq,
string &digits,
int level,
vector<string> &result,string trans[])
{
if(level == digits.size()){
result.push_back(seq);
return;
}
int group = digits[level] - 48;
for(int i=0; i<trans[group].size(); i++){
seq.push_back(trans[group][i]);
getLetterCombination(seq,digits,level+1,result,trans);
seq.resize(seq.size()-1);
}
}
vector<string> letterCombinations(string digits) {
string trans[] = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
vector<string> result;
string seq;
getLetterCombination(seq,digits,0,result,trans);
return result;
}