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"].
代码及思路:
方法1,循环
方法2,Backtrack
class Solution {
public:
/*vector<string> letterCombinations(string digits) {
vector<string> res(1,"");
string charmap[10] = {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
for(int i = 0; i < digits.size(); i++){
vector<string> tempres;
for(int c = 0; c < charmap[digits[i] - '0'].size(); c++){
for(int j = 0; j < res.size(); j++){
tempres.push_back(res[j] + charmap[digits[i] - '0'][c]);
}
}
res = tempres;
}
if ((res.size()==1)&&(res[0] == "")) res.clear();// clear()
return res;
}*/
vector<string> letterCombinations(string digits){
string charmap[10] = {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
vector<string> res;
string local;
backtracking(charmap, digits, res, 0, local);
if ((res.size()==1)&&(res[0] == "")) res.clear();// clear()
//atention: string s, s default ""
return res;
}
void backtracking(const string m[], const string& digits, vector<string>& res, int index, string& local){
// const string& m[] ,error:declaration of 'm' as array of references
if(index == digits.size()){
res.push_back(local);
}else{
for(int c = 0; c < m[digits[index] - '0'].size(); c++){
local.push_back(m[digits[index] - '0'][c]);
backtracking(m, digits, res, index + 1, local);
local.pop_back();
}
}
}
};