DSA - letter combinations of a phone number - C++,Dynamic Programming

Hey, so today we are going to solve Leetcode - letter combinations of a phone number

Problem Link- https://leetcode.com/problems/letter-combinations-of-a-phone-number/

class Solution {
public:

    void solve(int start, string mapping[], string digits, vector<string>&ans, string s) {

     if(start == digits.length()){
      ans.push_back(s);
      return;
     }

     int num= digits[start]-'0';
     int val = mapping[num];

     for(int i =0; i<val; i++){
      s.push_back(val[i]);
      solve(start+1, mapping, digits, ans, s);
      s.pop_back();
     }

    }

     vector<string> letterCombinations(string digits) {

     vector<string> ans;
     if(digits.length() == 0){
      return ans;
     }
     int start = 0; 
     string s = "";
     string mapping[10] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; 

     solve(start, mapping, digits, ans, s);
     return ans;
     }
}

Here's how the code works:

  • We define a function letterCombinations that takes a string digits representing the phone number as input and returns a vector of strings containing all possible combinations of letters corresponding to the phone number.

  • We first create a mapping vector that maps each digit to the corresponding set of letters on a phone keypad.

  • We then call a helper function solve that takes the digits string, the mapping vector, the s string that stores the current combination of letters being generated, and the ans vector that stores all valid combinations of letters generated so far.

  • In the solve function, we check if the s string has the same length as the digits string. If it does, then we have generated a valid combination of letters and add it to the ans vector.

  • If the s string is not yet of the same length as the digits string, we get the current digit and its corresponding set of letters from the mapping vector, and iterate over all the letters in the set.

  • For each letter, we add it to the s string, and recursively call solve with the updated s string.

  • After the recursive call returns, we remove the last letter added to s, and try the next letter in the set.

  • Finally, in the main function, we call letterCombinations with the phone number digits = "23", and print out all the valid combinations of letters returned by the function.