I used recursion to solve it. Here is my code

#include<iostream>
using namespace std;
void keypad(int n, int m, int x, int y, string arr[]){
    if(arr[n][x]=='\0' || arr[m][y]=='\0'){
        return;
    }
    cout<<arr[n][x]<<arr[m][y]<<endl;
    keypad(n, m, x+1, y, arr);
    keypad(n, m, x, y+1, arr);
    
}
int main(){
    int n,m;
    cin>>n>>m;
    string arr[]={"","./","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
    keypad(n,m,0,0,arr);
    return 0;
}

But i am getting some repeated combinations in output and i am unable to understand why? My output:

2 3
ad
bd
cd
ce
cf
be
ce
cf
bf
be
ce
cf
bf
cf
af
bf
cf

I don't know why am getting repeated combinations in output like am getting "ce" three times. I don't know where did i make a mistake..

My expected output is:

 2 3
 ad
 bd
 cd
 ae
 be
 ce
 af
 bf
 cf
1

There are 1 best solutions below

0
zdf On

You probably think that the two keypad calls are independent. They are not: when you make the second call - keypad(n, m, x, y+1, arr), the first one will be called again because... it's the first. You must add a condition and call one or the other, but not both.

Add tracing code to your function to better understand what you are doing:

// ...
cout << x << " " << y << endl;
cout << arr[n][x] << arr[m][y] << endl;
// ...

The non-recursive solution is straightforward:

string first = arr[n];
string second = arr[m];
for (auto f : first)
  for (auto s : second)
    cout << f << s << endl;

And here's the recursive solution - it is just a translation of the iterative solution:

void print(string first, string second, int i = 0, int j = 0)
{
  cout << first[i] << second[j] << endl;
  if (++i < first.length())
    print(first, second, i, j);
  else if ( ++j < second.length())
    print(first, second, 0, j);
}