Skip to content

Commit 013d122

Browse files
authored
feat: add recursion subsets (#5503)
1 parent e493eb2 commit 013d122

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package com.thealgorithms.Recursion;
2+
3+
// program to find power set of a string
4+
5+
import java.util.ArrayList;
6+
import java.util.List;
7+
8+
public final class GenerateSubsets {
9+
10+
private GenerateSubsets() {
11+
throw new UnsupportedOperationException("Utility class");
12+
}
13+
14+
public static List<String> subsetRecursion(String str) {
15+
return doRecursion("", str);
16+
}
17+
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;
23+
}
24+
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));
31+
32+
left.addAll(right);
33+
34+
return left;
35+
}
36+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package com.thealgorithms.Recursion;
2+
3+
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
4+
5+
import java.util.List;
6+
import org.junit.jupiter.api.Test;
7+
8+
public final class GenerateSubsetsTest {
9+
10+
@Test
11+
void subsetRecursionTestOne() {
12+
String str = "abc";
13+
String[] expected = new String[] {"abc", "ab", "ac", "a", "bc", "b", "c", ""};
14+
15+
List<String> ans = GenerateSubsets.subsetRecursion(str);
16+
assertArrayEquals(ans.toArray(), expected);
17+
}
18+
19+
@Test
20+
void subsetRecursionTestTwo() {
21+
String str = "cbf";
22+
String[] expected = new String[] {"cbf", "cb", "cf", "c", "bf", "b", "f", ""};
23+
24+
List<String> ans = GenerateSubsets.subsetRecursion(str);
25+
assertArrayEquals(ans.toArray(), expected);
26+
}
27+
28+
@Test
29+
void subsetRecursionTestThree() {
30+
String str = "aba";
31+
String[] expected = new String[] {"aba", "ab", "aa", "a", "ba", "b", "a", ""};
32+
33+
List<String> ans = GenerateSubsets.subsetRecursion(str);
34+
assertArrayEquals(ans.toArray(), expected);
35+
}
36+
}

0 commit comments

Comments
 (0)