#include <bits/stdc++.h>
using namespace std;
class Solution {
private:
void solve(string output, vector<string>& ans, int index, vector<string>& mapping, const string& digits) {
// Base case: If index reaches the end of the input digits
if (index >= digits.size()) {
ans.push_back(output);
return;
}
// Convert the current digit to an integer index
int number = digits[index] - '0';
// Check if the index is valid (bounds check)
if (number < 0 || number >= mapping.size()) {
return;
}
// Get the corresponding letters for the current digit
string values = mapping[number];
// Loop through each character in the string values
for (char c : values) {
output.push_back(c);
solve(output, ans, index + 1, mapping, digits);
output.pop_back(); // Backtrack
}
}
public:
vector<string> letterCombinations(string digits) {
// Handle edge case for empty input
if (digits.empty()) {
return {};
}
// Define the mapping of digits to their corresponding characters
vector<string> mapping = { " ", " ", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
// Variables for the recursive call
string output = "";
vector<string> ans;
// Call the recursive solver
solve(output, ans, 0, mapping, digits);
return ans; // Return the computed result
}
};
int main() {
Solution sol;
string digits = "23";
vector<string> result = sol.letterCombinations(digits);
// Output the result
for (const string& str : result) {
cout << str << " ";
}
cout << endl;
return 0;
}
I2luY2x1ZGUgPGJpdHMvc3RkYysrLmg+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7CgpjbGFzcyBTb2x1dGlvbiB7CnByaXZhdGU6IAogICAgdm9pZCBzb2x2ZShzdHJpbmcgb3V0cHV0LCB2ZWN0b3I8c3RyaW5nPiYgYW5zLCBpbnQgaW5kZXgsIHZlY3RvcjxzdHJpbmc+JiBtYXBwaW5nLCBjb25zdCBzdHJpbmcmIGRpZ2l0cykgewogICAgICAgIC8vIEJhc2UgY2FzZTogSWYgaW5kZXggcmVhY2hlcyB0aGUgZW5kIG9mIHRoZSBpbnB1dCBkaWdpdHMKICAgICAgICBpZiAoaW5kZXggPj0gZGlnaXRzLnNpemUoKSkgewogICAgICAgICAgICBhbnMucHVzaF9iYWNrKG91dHB1dCk7CiAgICAgICAgICAgIHJldHVybjsKICAgICAgICB9CgogICAgICAgIC8vIENvbnZlcnQgdG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