lintcode-425-电话号码的字母组合
425-电话号码的字母组合
Given a digit string excluded 01, 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.注意事项
以上的答案是按照词典编撰顺序进行输出的,不过,在做本题时,你也可以任意选择你喜欢的输出顺序。
样例
给定 "23"
返回 ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]标签
递归 回溯法 字符串处理 脸书 优步
思路
使用回溯 + 递归
code
class Solution {
public:
/*
* @param digits: A digital string
* @return: all posible letter combinations
*/
vector<string> letterCombinations(string digits) {
// write your code here
if (digits.size() <= 0) {
return vector<string>();
}
vector<string> result;
string str;
letterCombinations(digits, str, 0, result);
return result;
}
void letterCombinations(string &digits, string &str, int index, vector<string> &result) {
if (index == digits.size()) {
result.push_back(str);
return;
}
string base[] = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
for (int i = 0; i < base[digits[index] - '0'].size(); i++) {
str += base[digits[index] - '0'][i];
letterCombinations(digits, str, index + 1, result);
str.pop_back();
}
}
};