Problem
17. Letter Combinations of a Phone Number
Question
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"].
思路
递归遍历所有组合
Code
class Solution {
public:
bool flag;
std::vector<string> result;
std::map<int, string> dic= {
{1, ""},
{2, "abc"},
{3, "def"},
{4, "ghi"},
{5, "jkl"},
{6, "mno"},
{7, "pqrs"},
{8, "tuv"},
{9, "wxyz"},
{-8, "+"},
{-48, " "},
{-13, "#"}
};
vector<string> letterCombinations(string digits) {
flag = false;
makeCombination(digits, digits.size(), "");
return result;
}
void makeCombination(string digits, int size, string s) {
if (size==0) {
if (s != "")
result.push_back(s);
return;
}
int n = (int)digits[0]-48;
if (n == 1)
makeCombination(digits.substr(1), size-1, s);
for (int i = 0; i < dic[n].size(); i++) {
string nstr = s;
if (n == 35 && flag) {
flag = false;
}
else if (n == 35 && !flag) {
flag = true;
}
else if (flag) {
nstr = s + (char)toupper(dic[n][i]);
}
else {
nstr = s + (char)(dic[n][i]);
}
makeCombination(digits.substr(1), size-1, nstr);
}
}
};
本文介绍了一个算法问题:给定一个数字字符串,返回该数字可能代表的所有字母组合。使用递归方式遍历所有可能的组合,并提供了一段C++实现代码。
557

被折叠的 条评论
为什么被折叠?



