题目要求如下:
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.
因为题目没有要求字母的排列顺序,所以处理起来相对容易很多。
题比较简单,用递归的方式就可以完成,因此就不做过多的思路介绍和代码注释了,看代码就可以明白。
代码如下,欢迎指导交流~
AC, Runtime: 8 ms
//LeetCode_Letter Combinations of Phone Number
//Written by zhou
//2013.11.27
class Solution {
public:
void MapLetters(const string *map, string &digits, string &str, int curLen, vector<string> &res)
{
if (curLen == digits.length()) //完成一个组合
{
res.push_back(str);
return;
}
for (int i = 0; i < map[digits[curLen]-'0'].length(); ++i)
{
str.push_back(map[digits[curLen]-'0'][i]);
MapLetters(map,digits,str,curLen+1,res);
str.pop_back();
}
}
vector<string> letterCombinations(string digits) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
const string map[10] = {"","","abc","def","ghi","jkl","mno","qprs","tuv","wxyz"};
vector<string> result;
string str(""); //临时字串
MapLetters(map,digits,str,0,result);
return result;
}
};