问题描述
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.
解题思路
枚举可能的所有情况。用一个vector保存所有string。每次取出vector的头元素并在该元素后逐个添加下一个数字对应的字母,把添加后的string再加入到vector中即可
代码如下
class Solution {
public:
vector<string> letterCombinations(string digits) {
string digitStr[] = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
int leng = digits.size();
vector<string> vecStr; //保存所有符合的字符串
if (leng == 0) return vecStr;
vecStr.push_back("");
for (int i = 0; i < leng; i++) { //进行digits位数次循环
int size = vecStr.size(); //获取已保存的首个字符串的size
for (int j = 0; j < size; j++) {
string current = vecStr[0]; //暂时保存首个字符串
vecStr.erase(vecStr.begin()); //删去首个串
for (int k = 0; k < digitStr[digits[i] - '0'].size(); k++) {
vecStr.push_back(current + digitStr[digits[i] - '0'][k]); //将删去的串加上当前digits对应的digitStr中的一个字母加入vecStr中
}
}
}
return vecStr;
}
};