您的位置:首页 > 其它

Letter Combinations of a Phone Number

2015-08-01 22:28 274 查看
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:
//回溯法
void DFS(string digits, int n, int curIndex, string curStr, unordered_map<char, string> &cmap, vector<string> &ans)
{
if(curIndex > n)
return;
if(curIndex == n)
{
ans.push_back(curStr);
return;
}

int tmpLen = cmap[digits[curIndex]].size();
for(int i = 0; i< tmpLen; ++i)
{
curStr.push_back(cmap[digits[curIndex]][i]);
DFS(digits, n, curIndex + 1, curStr, cmap, ans);
curStr.pop_back();
}
}

vector<string> letterCombinations(string digits) {
int len = digits.size();
vector<string> ans;
if(len >= 1)
{
unordered_map<char, string> cmap;
cmap['2'] = "abc";
cmap['3'] = "def";
cmap['4'] = "ghi";
cmap['5'] = "jkl";
cmap['6'] = "mno";
cmap['7'] = "pqrs";
cmap['8'] = "tuv";
cmap['9'] = "wxyz";
string curStr = "";
DFS(digits, len, 0, curStr, cmap, ans);
}

return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息