I have copied this code from GeeksForGeeks and couldn't understand how this works.
please @Anuj-Kumar-Sharma bhaiya explain this code in your next video I think many of us will get help from this algorithm.
//java code
public class Subsequence {
// str : storse input string
// n : length of str
// curr : stores current permutation
// index : index in current(curr) permutation
static void printSubSeqRec(String str, int n, int index, String curr) {
System.out.println(curr);
for (int i = index + 1; i < n; i++) {
curr += str.charAt(i);
printSubSeqRec(str, n, i, curr);
// backtracking
curr = curr.substring(0, curr.length() - 1);
}
}
// Generates power set in lexicographic order
static void printSubSeq(String str) {
int index = -1;
String curr = "";
printSubSeqRec(str, str.length(), index, curr);
}
public static void main(String[] args) {
String str = "cab";
printSubSeq(str);
}
}
output of this code comes to be
I recommend you to run the below code as well for clarity where I have given different print statements.
public class SubsequenceRecursion {
// str : storse input string
// n : length of str
// curr : stores current permutation
// index : index in current(curr) permutation
static void printSubSeqRec(String str, int n, int index, String curr) {
System.out.println(curr+"\n");
for (int i = index + 1; i < n; i++) {
curr += str.charAt(i);
System.out.println("inside loop i is " + i);
System.out.println("inside loop index is " + index);
printSubSeqRec(str, n, i, curr);
System.out.println("Before backtracking " + curr);
System.out.println("i is " + i);
System.out.println("index is " + index);
// backtracking
curr = curr.substring(0, curr.length() - 1);
System.out.println("After backtracking " + curr);
}
}
// Generates power set in lexicographic order
static void printSubSeq(String str) {
int index = -1;
String curr = "";
printSubSeqRec(str, str.length(), index, curr);
}
public static void main(String[] args) {
String str = "cab";
printSubSeq(str);
}
}