Letter Combinations of a Phone Number LeetCode solution in C++

1
class Solution {
2
public:
3
void solve(string digit, string output, int index, vector<string> &ans,
4
string mapping[]) { // base condition
5
if (index >= digit.length()) {
6
ans.push_back(output);
7
return;
8
}
9
// digit[index] gives character value to change in integer subtract '0'
10
int number = digit[index] - '0';
11
// get the string at perticular index in mapping
12
string value = mapping[number];
13
// runs loop in value string and push that value in out put string ans do
14
// recursive call for next index
15
for (int i = 0; i < value.length(); i++) {
16
output.push_back(value[i]);
17
solve(digit, output, index + 1, ans, mapping);
18
// backtrack
19
// backtrach because initially output is empty and one case solves now you
20
// have to solve second case in similar way
21
output.pop_back();
22
}
23
}
24

25
vector<string> letterCombinations(string digits) {
26
vector<string> ans;
27
// if it is empty input string
28
if (digits.length() == 0) {
29
return ans;
30
}
31
string output = "";
32
int index = 0;
33
// map every index with string
34
string mapping[10] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
35
solve(digits, output, index, ans, mapping);
36
return ans;
37
}
38
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0