fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. class Solution {
  5. private:
  6. void solve(string output, vector<string>& ans, int index, vector<string>& mapping, const string& digits) {
  7. // Base case: If index reaches the end of the input digits
  8. if (index >= digits.size()) {
  9. ans.push_back(output);
  10. return;
  11. }
  12.  
  13. // Convert the current digit to an integer index
  14. int number = digits[index] - '0';
  15.  
  16. // Check if the index is valid (bounds check)
  17. if (number < 0 || number >= mapping.size()) {
  18. return;
  19. }
  20.  
  21. // Get the corresponding letters for the current digit
  22. string values = mapping[number];
  23.  
  24. // Loop through each character in the string values
  25. for (char c : values) {
  26. output.push_back(c);
  27. solve(output, ans, index + 1, mapping, digits);
  28. output.pop_back(); // Backtrack
  29. }
  30. }
  31.  
  32. public:
  33. vector<string> letterCombinations(string digits) {
  34. // Handle edge case for empty input
  35. if (digits.empty()) {
  36. return {};
  37. }
  38.  
  39. // Define the mapping of digits to their corresponding characters
  40. vector<string> mapping = { " ", " ", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
  41.  
  42. // Variables for the recursive call
  43. string output = "";
  44. vector<string> ans;
  45.  
  46. // Call the recursive solver
  47. solve(output, ans, 0, mapping, digits);
  48.  
  49. return ans; // Return the computed result
  50. }
  51. };
  52.  
  53. int main() {
  54. Solution sol;
  55. string digits = "23";
  56. vector<string> result = sol.letterCombinations(digits);
  57.  
  58. // Output the result
  59. for (const string& str : result) {
  60. cout << str << " ";
  61. }
  62. cout << endl;
  63.  
  64. return 0;
  65. }
  66.  
Success #stdin #stdout 0.01s 5284KB
stdin
Standard input is empty
stdout
ad ae af bd be bf cd ce cf