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();
}
}
};