I've been trying some recursion and backtracking problems. Done some questions like printing the subsequences, permutations, N-Queen which are base questions for these approaches. Now, what I've got to know is that we have to trust that the recursion will work and we just have to do our part of the problem and leave the remaining on the recursion.
Now, using this approach I was doing a problem in which we are given an array of keys of a keypad and we just have to print the combinations of the characters at particular keys(indices) of this array.
public class Keypad {
static String pad[] = { " ", ".+@$", "abc", "def", "ghi", "jkl" , "mno", "pqrs" , "tuv", "wxyz" };
static void keypad(String str, String result) {
if(str.length() == 0) {
System.out.println(result);
return;
}
for(int i = 0; i < str.length(); i++) {
char currKey = str.charAt(0);
String key = pad[Integer.parseInt(""+currKey)];
for(int j = 0; j < key.length(); j++) {
char currChar = key.charAt(j);
keypad(str.substring(1), result + currChar);
}
}
}
public static void main(String[] args) {
String string = "12";
keypad(string, "");
}
}
Required output -
.a .b .c +a +b +c @a @b @c $a $b $c (in newlines)
My output -
.a .b .c +a +b +c @a @b @c $a $b $c .a .b .c +a +b +c @a @b @c $a $b $c (in newlines)
Now, this is pretty straightforward without using recursion, directly using the loops to do it but here I am getting confused. What I did was I used the loop for the first input "1" and sent the other ones to the recursion by str.substring(1)
.
This code is partially working as it's printing the output twice, though I have a feeling that somewhere in the recursion tree, it is happening but I need to understand how to grasp this and how to find bugs in this type of program. Also, on a side note, this was my first question on stackOverFlow so if any suggestions are there related to posting questions or if anything is missing, do tell me. Thanks!