Leetcode 17. Letter Combinations of a Phone Number

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Letter Combinations of a Phone Number

2. Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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);
}
}
};

Reference

  1. https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/
如果有收获,可以请我喝杯咖啡!