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 , string &digits){
  7. if(index>=digits.size()){
  8. ans.push_back(output);
  9. return;
  10. }
  11. int number = digits[index] - '0';
  12. if (number < 2 || number >9){
  13. return;
  14. }
  15. string values = mapping[number];
  16. for(char c : values){
  17. output.push_back(c);
  18. solve(output , ans , index+1, mapping , digits);
  19. output.pop_back();
  20. }
  21. }
  22. public:
  23. vector<string> letterCombinations(string digits) {
  24. if(digits.empty()) return {};
  25. string output = "";
  26. int index = 0;
  27. vector<string>ans;
  28. vector<string>mapping = {" ", " ", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
  29. solve(output,ans,index,mapping,digits);
  30. return ans;
  31. }
  32. };
  33.  
  34. int main() {
  35. Solution sol;
  36.  
  37. // Input string for which we want to compute combinations
  38. string digits = "23";
  39.  
  40. // Call the method to get the letter combinations
  41. vector<string> result = sol.letterCombinations(digits);
  42.  
  43. // Output the result
  44. cout << "Letter Combinations for input \"23\":\n";
  45. for (const string& str : result) {
  46. cout << str << " ";
  47. }
  48. cout << endl;
  49.  
  50. return 0;
  51. }
  52.  
Success #stdin #stdout 0s 5280KB
stdin
Standard input is empty
stdout
Letter Combinations for input "23":
ad ae af bd be bf cd ce cf