forked from MTalhaofc/HacktoberFest-2024
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Letter Combinations of a Phone Number
39 lines (36 loc) · 1.09 KB
/
Letter Combinations of a Phone Number
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
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
vector<string> letterCombinations(string digits) {
string mapping[] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
vector<string> result;
if (digits.empty()) return result;
backtrack(result, mapping, digits, "", 0);
return result;
}
private:
void backtrack(vector<string>& result, string mapping[], const string& digits, string current, int index) {
if (current.length() == digits.length()) {
result.push_back(current);
return;
}
int digit = digits[index] - '0';
string letters = mapping[digit];
for (char letter : letters) {
backtrack(result, mapping, digits, current + letter, index + 1);
}
}
};
int main() {
Solution solution;
string input = "23";
vector<string> combinations = solution.letterCombinations(input);
for (const string& combo : combinations) {
cout << combo << " ";
}
cout << endl;
return 0;
}