- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrintSubsets.java
More file actions
Latest commit
44 lines (42 loc) · 1.65 KB
/
Copy pathPrintSubsets.java
File metadata and controls
44 lines (42 loc) · 1.65 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
packageRecursionAndBacktracking;
/* We have given a string, and we have to print all the substrings of the given string(Power set : set of all subsets)
Example:
Input : ab
Output : {" ", "a", "b", "ab"}
*/
importjava.util.Scanner;
publicclassPrintSubsets {
publicstaticvoidprintSubsets(Stringoutput, Stringinput){
// Base Case
if(input.equals("")){
if(output.equals("")){ // if the output string is empty then print " "
System.out.println("\"\"");
}else { // else print output string
System.out.println("\"" + 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
printSubsets(outputLeft, input);
printSubsets(outputRight, input);
}
publicstaticvoidmain(String[] args) {
Scannersc = newScanner(System.in);
System.out.println("Enter number of testCases:");
intt = sc.nextInt();
while (t-- > 0){
System.out.println("Enter the input string:");
Stringinput = sc.next();
Stringoutput = "";
printSubsets(output, input);
}
}
}