Subsets of a String | java

 

Subsets of a String | Java

In Java, a subset refers to a collection of elements that is formed by selecting some or all elements from a larger set without changing the order.



package Backtracking;

//print subset of string using backtracking
public class subset {
    public static void printSubset(String str, String set, int i) {
        if (i == str.length()) {
            System.out.println(set);
            return;
        }

        // for yes condition
        printSubset(str, set + str.charAt(i), i + 1);

        // for no condition
        printSubset(str, set, i + 1);

    }

    public static void main(String[] args) {
        String str = "abc";
        String subSet = "";
        printSubset(str, subSet, 0);

    }
}


Output:

abc
ab
ac
a
bc
b
c

This Java code demonstrates how to print all subsets of a given string using backtracking.

Let's break down the code:

  1. The printSubset method is a recursive function that takes three parameters:

    • str: The original string for which subsets are to be found.
    • set: The current subset being constructed.
    • i: The index indicating the position of the current character in the original string.
  2. Inside the printSubset method:

    • If i is equal to the length of the input string str, it means we have reached the end of the string, so we print the current subset set.
    • Otherwise, for each character at index i in the original string:
      • We include the current character in the subset and recursively call printSubset with the updated set and i+1.
      • We exclude the current character from the subset and recursively call printSubset with the original set and i+1.
  3. In the main method:

    • We define the input string str as "abc".
    • We initialize an empty string subSet.
    • We call the printSubset method with the input string str, empty string subSet, and index 0 to start the recursive process.
  4. During the execution of the printSubset method, it recursively explores all possible combinations of including or excluding each character from the original string until it reaches the end of the string. This way, it generates and prints all possible subsets of the given string "abc".


No comments: