# All subsets of a String in java using recursion

I wrote this code for printing all sets of a String. It also prints the empty subset. Is this the right approach

public class AllSubSet {

public static void allSet(String s, String t) {
System.out.print(t + " ");
if (s.length() > 0) {
for (int i = 0; i < s.length(); i++) {
allSet(s.substring(i + 1, s.length()), t + s.charAt(i));
}
}
}

public static void main(String args[]) {
String a = "ABC";
String t = "";
allSet(a, t);
}
}

• What would be the intended output if the input string has duplicate characters (e.g. "ABBCA")? – Martin R Jul 9 '18 at 12:21

If I have understood correctly, you're aiming for all subset of a String. Through your code for String = "ABC"; //Result is -- > A AB ABC AC B BC C

However, for

String = "ABB";
// Result is --> A AB ABB AB B BB B (You see AB twice as well as letter B).


So to make it more clear for unique subsets, added a set implementation.

TreeSet (extra sorted feature over hash), as below : (using same recursion)

public class Test {

public static void allSet(String s, String t, Set<String> set) {
// System.out.print(t + " ");   will print later.
if(!"".equalsIgnoreCase(t))
if (s.length() > 0) {
for (int i = 0; i < s.length(); i++) {
allSet(s.substring(i + 1, s.length()), t + s.charAt(i),set);
}
}
}
public static void main(String args[]) {
String a = "ABB";
String t = "";
Set<String> set = new TreeSet<String>();
allSet(a, t, set);
System.out.println(set.toString());
}

// Now, result --> [A, AB, ABB, B, BB]

• We are not just looking for alternative implementations, but want to improve the future coding of the OP and everyone else. So you should describe why this is different and why it is better. At least include what is currently in your comment under the OP's question. – Graipher Jul 9 '18 at 10:12
• sure @Graipher , make sense.Let me enhance. – Vivek Jul 9 '18 at 10:15
• This solution does not produce same results as the code in the question. Missing "AC" – Sharon Ben Asher Jul 9 '18 at 10:19
• This prints all (contiguous) substrings of the given string, not all subsets that can be formed with characters of the given string. – Martin R Jul 9 '18 at 11:36
• I have written the code only for the string having unique characters. Your code combines both unique and repeated characters. Thanks. – Curious Jul 13 '18 at 9:29