-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathletter_combinations.cpp
More file actions
84 lines (75 loc) · 2.01 KB
/
letter_combinations.cpp
File metadata and controls
84 lines (75 loc) · 2.01 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*
* =====================================================================================
*
* Filename: letter_combinations.cpp
*
* Description: 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.
*
* Version: 1.0
* Created: 02/15/19 02:41:12
* Revision: none
* Compiler: gcc
*
* Author: Zhu Xianfeng (), xianfeng.zhu@gmail.com
* Organization:
*
* =====================================================================================
*/
#include <stdio.h>
#include <string>
#include <vector>
#include <map>
class Solution
{
public:
std::vector<std::string> letterCombinations(const std::string& digits)
{
std::vector<std::string> combs;
if (digits.length() > 0)
{
combine(digits, 0, std::string(), combs);
}
return combs;
}
int combine(const std::string& digits, int idx, const std::string& prefix, std::vector<std::string>& combs)
{
static std::map<char, std::string> letters = {
{'2', "abc"},
{'3', "def"},
{'4', "ghi"},
{'5', "jkl"},
{'6', "mno"},
{'7', "pqrs"},
{'8', "tuv"},
{'9', "wxyz"},
};
if (prefix.length() == digits.length())
{
combs.push_back(prefix);
return 0;
}
auto iter = letters.find(digits[idx]);
if (iter == letters.end())
{
// Invalid digit
return -1;
}
for (auto chr: iter->second)
{
combine(digits, idx + 1, prefix + chr, combs);
}
return 0;
}
};
int main(int argc, char* argv[])
{
const std::string digits = "23";
auto combs = Solution().letterCombinations(digits);
for (const auto& s: combs)
{
printf("%s\n", s.c_str());
}
return 0;
}