|
1 | 1 | package com.thealgorithms.recursion; |
2 | 2 |
|
3 | | -// program to find power set of a string |
4 | | - |
5 | 3 | import java.util.ArrayList; |
6 | 4 | import java.util.List; |
7 | 5 |
|
| 6 | +/** |
| 7 | + * Utility class to generate all subsets (power set) of a given string using recursion. |
| 8 | + * |
| 9 | + * <p>For example, the string "ab" will produce: ["ab", "a", "b", ""] |
| 10 | + */ |
8 | 11 | public final class GenerateSubsets { |
9 | 12 |
|
10 | 13 | private GenerateSubsets() { |
11 | | - throw new UnsupportedOperationException("Utility class"); |
12 | 14 | } |
13 | 15 |
|
| 16 | + /** |
| 17 | + * Generates all subsets (power set) of the given string using recursion. |
| 18 | + * |
| 19 | + * @param str the input string to generate subsets for |
| 20 | + * @return a list of all subsets of the input string |
| 21 | + */ |
14 | 22 | public static List<String> subsetRecursion(String str) { |
15 | | - return doRecursion("", str); |
| 23 | + return generateSubsets("", str); |
16 | 24 | } |
17 | 25 |
|
18 | | - private static List<String> doRecursion(String p, String up) { |
19 | | - if (up.isEmpty()) { |
20 | | - List<String> list = new ArrayList<>(); |
21 | | - list.add(p); |
22 | | - return list; |
| 26 | + /** |
| 27 | + * Recursive helper method to generate subsets by including or excluding characters. |
| 28 | + * |
| 29 | + * @param current the current prefix being built |
| 30 | + * @param remaining the remaining string to process |
| 31 | + * @return list of subsets formed from current and remaining |
| 32 | + */ |
| 33 | + private static List<String> generateSubsets(String current, String remaining) { |
| 34 | + if (remaining.isEmpty()) { |
| 35 | + List<String> result = new ArrayList<>(); |
| 36 | + result.add(current); |
| 37 | + return result; |
23 | 38 | } |
24 | 39 |
|
25 | | - // Taking the character |
26 | | - char ch = up.charAt(0); |
27 | | - // Adding the character in the recursion |
28 | | - List<String> left = doRecursion(p + ch, up.substring(1)); |
29 | | - // Not adding the character in the recursion |
30 | | - List<String> right = doRecursion(p, up.substring(1)); |
| 40 | + char ch = remaining.charAt(0); |
| 41 | + String next = remaining.substring(1); |
| 42 | + |
| 43 | + // Include the character |
| 44 | + List<String> withChar = generateSubsets(current + ch, next); |
31 | 45 |
|
32 | | - left.addAll(right); |
| 46 | + // Exclude the character |
| 47 | + List<String> withoutChar = generateSubsets(current, next); |
33 | 48 |
|
34 | | - return left; |
| 49 | + withChar.addAll(withoutChar); |
| 50 | + return withChar; |
35 | 51 | } |
36 | 52 | } |
0 commit comments