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
You probably think that the two
keypadcalls 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:
The non-recursive solution is straightforward:
And here's the recursive solution - it is just a translation of the iterative solution: