- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrintUniqueSubsets.java
More file actions
Latest commit
48 lines (46 loc) · 1.73 KB
/
Copy pathPrintUniqueSubsets.java
File metadata and controls
48 lines (46 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
packageRecursionAndBacktracking;
/*
* We have given a string, and we have to print the unique not repeated subsets of the given string.
* Example :
* String : "aab"
* Output : "", "a", "b", "aa", "ab", "aab"
*
*
* Hint : For this we simply store the result into Set in the base case.
*/
importjava.util.HashSet;
importjava.util.Scanner;
importjava.util.Set;
publicclassPrintUniqueSubsets {
staticSet<String> set = newHashSet<>();
publicstaticvoidprintUniqueSubsets(Stringoutput, Stringinput){
// Base Case
if(input.equals("")){
if(output.equals("")){ // if the output string is empty then print " "
set.add("\"\"");
}else { // else print output string
set.add("\"" + output + "\"");
}
return;
}
// divide the tree into two child left and right
StringoutputLeft = output;
StringoutputRight = output;
// For left child : we take output string as it is before
// For right child : we take output string by appending the 0th character of the input string
outputRight += input.charAt(0);
// Now update input string by deleting 0th character of the input string
input = input.substring(1);
// Now simply call the recursive function
printUniqueSubsets(outputLeft, input);
printUniqueSubsets(outputRight, input);
}
publicstaticvoidmain(String[] args) {
Scannersc = newScanner(System.in);
System.out.println("Enter the input string:");
Stringinput = sc.next();
Stringoutput = "";
printUniqueSubsets(output, input);
System.out.println(set);
}
}