For my string input "aaa" I want the answer to be
[[],[a],[a,a],[a,a,a]]
My code:
import java.util.*;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String a = "aaa";
char arr[] = a.toCharArray();
Arrays.sort(arr);
List<List<Character>> big = new ArrayList<List<Character>>();
subset(arr, 0, big, new ArrayList<Character>(), true);
System.out.println(big);
}
static void subset(char arr[], int count, List<List<Character>> big,
List<Character> temp, boolean flag) {
if (count == arr.length) {
big.add(new ArrayList<Character>(temp));
return;
}
if (flag == false && arr[count] == arr[count - 1]) {
// logic for unique subset
subset(arr, count + 1, big, temp, false);
} else {
temp.add(arr[count]);
subset(arr, count + 1, big, temp, true);
temp.remove(temp.size() - 1);
subset(arr, count + 1, big, temp, false);
}
}
}
This code gave me this output:
[[a, a, a], [a, a], [a], []]
but I want this as: Required output:
[[],[a],[a,a],[a,a,a]]
Also the logic which I wrote for getting unique subset can also be done using a collection like TreeSet
and HashSet
.
I tried using TreeSet
the answer was in sorted order and unique subset but with some extra commas.
It would be really helpful if someone would solve my both problems.