[Solved] Letter combinations of a phone number


The problem is that you’re both looping and recursing.

print("22", "", 0);

will recurse into

print("22", "a", 1);
print("22", "b", 1);
print("22", "c", 1);
print("22", "a", 2);
print("22", "b", 2);
print("22", "c", 2);

and your extra bits are the last three calls.

Get rid of the loop over the input digits (you’re already doing that step by recursing):

 void print(string digits, string st, int pos)
 {
     if(digits.size() == pos)
     {
         ans.push_back(st);
     }
     else
     {
         int ch = digits[pos] - '0';
         for(int j = 0; j < 4 && ph[ch][j] != '0'; j++)
         {
             print(digits, st + ph[ch][j], pos + 1);
         }
     }
 }

(You also forgot to terminate some of your arrays, but that’s a different issue.)

solved Letter combinations of a phone number