文章作者:Tyan
博客:noahsnail.com | CSDN |
1. Description
2. Solution
class Solution {
public:
vector letterCombinations(string digits) {
vector result;
int n = digits.length();
if(n == 0) {
return result;
}
map m = {
{'2', "abc"},
{'3', "def"},
{'4', "ghi"},
{'5', "jkl"},
{'6', "mno"},
{'7', "pqrs"},
{'8', "tuv"},
{'9', "wxyz"}
};
vector values;
for(char ch : digits) {
values.push_back(m[ch]);
}
traverse(result, values, n, 0, "");
return result;
}
private:
void traverse(vector& result, vector& values, int& n, int current, string s) {
if(current == n) {
result.push_back(s);
return;
}
for(char ch : values[current]) {
string temp = s;
temp += ch;
traverse(result, values, n, current + 1, temp);
}
}
};
Reference
- https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/