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"].
思路:简单的回溯法
class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string> table={"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
vector<string> res;
if (digits.empty()) return res;
scan(0, "", digits, table, res);
return res;
}
void scan(int level, string path, string &digits, vector<string> &table,vector<string> &res){
if (level == digits.size()){
res.push_back(path);
return;
}
for (int i = 0; i < table[digits[level] - '0'].size(); i++){
path.push_back(table[digits[level] - '0'][i]);
scan(level + 1, path, digits, table, res);
path.pop_back();
}
}
};