#include<iostream>
using namespace std;
#include<vector>
#include<unordered_map>
class Solution
{
public:
vector<string> letterCombinations(string digits)
{
vector<string>combinations;
if (digits.empty())
{
return combinations;
}
unordered_map<char, string>aaa
{
{'2', "abc"},
{'3', "def"},
{'4', "ghi"},
{'5', "jkl"},
{'6', "mno"},
{'7', "pqrs"},
{'8', "tuv"},
{'9', "wxyz"}
};
string combination;
backtrack(combinations, aaa, digits, 0, combination);
return combinations;
}
void backtrack(vector<string>& combinations, const unordered_map<char, string>& aaa, const string& digits, int index, string& combination)
{
if (index == digits.length())
{
combinations.push_back(combination);
}
else
{
char digit = digits[index];
string letters = aaa.at(digit);
for (const char& letter : letters)
{
combination.push_back(letter);
backtrack(combinations, aaa, digits, index + 1, combination);
combination.pop_back(); //
}
}
}
};
int main()
{
Solution aaaa;
string b = "256";
aaaa.letterCombinations(b);
system("pause");
return 0;
}
#include<iostream>
using namespace std;
#include<vector>
#include<unordered_map>
class Solution
{
public:
vector<string>result;
string s;
void backtracking(const string& digits, int index) //(bbb, 0)
{
if (index == digits.size())
{
result.push_back(s);
return;
}
//int digit = digits[index]; // 传入的是字符串,要想变为数字需改变
int digit = digits[index] - '0'; // 将index指向的数字转为int
string letters = letterMap[digit]; // 取数字对应的字符集
for (int i = 0; i < letters.size(); i++)
{
s.push_back(letters[i]); // 处理
backtracking(digits, index + 1); // 递归,注意index+1,一下层要处理下一个数字了
s.pop_back(); // 回溯
}
}
private:
const string letterMap[10] =
{
"",
"",
"abc",
"def",
"ghi",
"jkl",
"mno",
"pqrs",
"tuv",
"wxyz",
};
};
int main()
{
Solution aaa;
string bbb = "256";
aaa.backtracking(bbb, 0);
system("pause");
return 0;
}
17 电话号码的字母组合
于 2023-01-09 21:04:23 首次发布