17. Letter Combinations of a Phone Number
题目
Given a string containing digits from 2-9 inclusive, 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. Note that 1 does not map to any letters.
解题思路
全排列的问题,考察dfs。直接看代码:
class Solution {
public:
void dfs(string s, int i, string out, vector<string> &res, vector<string> &mp) {
if (i == s.size()) {res.push_back(out); return;}
string str = mp[s[i] - '0'];
for (int j = 0; j < str.size(); ++j) {
dfs(s, i + 1, out + str[j], res, mp);
}
}
vector<string> letterCombinations(string digits) {
if (digits.empty()) return {};
vector<string> mp = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
vector<string> res;
dfs(digits, 0, "", res, mp);
return res;
}
};