Recursion Subset, Subsequences, String

1. skipChar Method: Excluding Specific Characters

Aman S
1 min readJan 23, 2024

Function: Generates subsequences of a given string while excluding occurrences of a specific character.

public static void skipChar(String p, String up) {
if (up.isEmpty()) {
System.out.println(p);
return;
}
if (up.charAt(0) == 'a') {
skipChar(p, up.substring(1));
} else {
skipChar(p + up.charAt(0), up.substring(1));
}
}

2. subseq Method (ArrayList as Argument): Storage for Later Use

Function: Generates all possible subsequences of a given string.

public static void generateSubseq(String p, String up) {
if (up.isEmpty()) {
System.out.println(p);
return;
}
// Take (or) include
generateSubseq(p + up.charAt(0), up.substring(1));
generateSubseq(p, up.substring(1));
}

3. subseq Method (ArrayList as Argument): Storage for Later Use

Function: Generates all possible subsequences of a given string and stores them in an ArrayList.

public static void subseq(String p, String up, ArrayList<String> result) {
if (up.isEmpty()) {
result.add(p);
return;
}
// Include the current character
subseq(p + up.charAt(0), up.substring(1), result);
// Exclude the current character
subseq(p, up.substring(1), result);
}

4. subseq Method (Overloaded): A Variant Approach

Function: An overloaded version of the subseq method also generates subsequences of a given string and stores them in an ArrayList

public static ArrayList<String> subseq(String p, String up) {
ArrayList<String> result = new ArrayList<>();
if (up.isEmpty()) {
result.add(p);
return result;
}
// Capture the results of recursive calls
ArrayList<String> included = subseq(p + up.charAt(0), up.substring(1));
ArrayList<String> excluded = subseq(p, up.substring(1));
// Add the results to the current result
result.addAll(included);
result.addAll(excluded);
return result;
}

--

--