Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions src/main/java/com/thealgorithms/Recursion/GenerateSubsets.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package com.thealgorithms.Recursion;

// program to find power set of a string

import java.util.ArrayList;
import java.util.List;

public final class GenerateSubsets {

private GenerateSubsets() {
throw new UnsupportedOperationException("Utility class");
}

public static List<String> subsetRecursion(String str) {
return doRecursion("", str);
}

private static List<String> doRecursion(String p, String up) {
if (up.isEmpty()) {
List<String> list = new ArrayList<>();
list.add(p);
return list;
}

// Taking the character
char ch = up.charAt(0);
// Adding the character in the recursion
List<String> left = doRecursion(p + ch, up.substring(1));
// Not adding the character in the recursion
List<String> right = doRecursion(p, up.substring(1));

left.addAll(right);

return left;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package com.thealgorithms.Recursion;

import static org.junit.jupiter.api.Assertions.assertArrayEquals;

import java.util.List;
import org.junit.jupiter.api.Test;

public final class GenerateSubsetsTest {

@Test
void subsetRecursionTestOne() {
String str = "abc";
String[] expected = new String[] {"abc", "ab", "ac", "a", "bc", "b", "c", ""};

List<String> ans = GenerateSubsets.subsetRecursion(str);
assertArrayEquals(ans.toArray(), expected);
}

@Test
void subsetRecursionTestTwo() {
String str = "cbf";
String[] expected = new String[] {"cbf", "cb", "cf", "c", "bf", "b", "f", ""};

List<String> ans = GenerateSubsets.subsetRecursion(str);
assertArrayEquals(ans.toArray(), expected);
}

@Test
void subsetRecursionTestThree() {
String str = "aba";
String[] expected = new String[] {"aba", "ab", "aa", "a", "ba", "b", "a", ""};

List<String> ans = GenerateSubsets.subsetRecursion(str);
assertArrayEquals(ans.toArray(), expected);
}
}