文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
Letter Combinations of a Phone Number2. Solution
class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string> result;
int n = digits.length();
if(n == 0) {
return result;
}
map<char, string> m = {
{'2', "abc"},
{'3', "def"},
{'4', "ghi"},
{'5', "jkl"},
{'6', "mno"},
{'7', "pqrs"},
{'8', "tuv"},
{'9', "wxyz"}
};
vector<string> values;
for(char ch : digits) {
values.push_back(m[ch]);
}
traverse(result, values, n, 0, "");
return result;
}
private:
void traverse(vector<string>& result, vector<string>& 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);
}
}
};
网友评论