Skip to content

Commit c7c3d8b

Browse files
committed
feat : new algo uniquesubseqcount
1 parent f34fe4d commit c7c3d8b

File tree

2 files changed

+82
-0
lines changed

2 files changed

+82
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package com.thealgorithms.dynamicprogramming;
2+
3+
// Program to find the number of Subsequences can be produced from a string
4+
5+
import java.util.Arrays;
6+
import java.util.HashSet;
7+
import java.util.Set;
8+
9+
// Author -> https://github.com/Tuhinm2002
10+
11+
public class UniqueSubsequencesCount {
12+
13+
private UniqueSubsequencesCount() {
14+
throw new UnsupportedOperationException("Utility class");
15+
}
16+
17+
public static int subseqCount(String str) {
18+
int[] dp = new int[str.length() + 1];
19+
for (int i : dp) {
20+
Arrays.fill(dp, -1);
21+
}
22+
int ans = recursiveCall(str, 0, dp);
23+
return ans;
24+
}
25+
26+
public static int recursiveCall(String st, int idx, int[] dp) {
27+
28+
if (idx >= st.length()) {
29+
return 0;
30+
}
31+
32+
if (dp[idx] != -1) {
33+
return dp[idx];
34+
}
35+
36+
Set<Character> set = new HashSet<>();
37+
38+
int res = 0;
39+
40+
for (int j = idx; j < st.length(); j++) {
41+
42+
if (set.contains(st.charAt(j))) {
43+
continue;
44+
}
45+
46+
set.add(st.charAt(j));
47+
48+
res = 1 + recursiveCall(st, j + 1, dp) + res;
49+
}
50+
51+
return dp[idx] = res;
52+
}
53+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package com.thealgorithms.dynamicprogramming;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
5+
import org.junit.jupiter.api.Test;
6+
7+
public class UniqueSubsequencesCountTest {
8+
9+
@Test
10+
void subseqCountTestOne() {
11+
String s = "abc";
12+
13+
assertEquals(7, UniqueSubsequencesCount.subseqCount(s));
14+
}
15+
16+
@Test
17+
void subseqCountTestTwo() {
18+
String s = "abcdashgdhas";
19+
20+
assertEquals(3592, UniqueSubsequencesCount.subseqCount(s));
21+
}
22+
23+
@Test
24+
void subseqCountTestThree() {
25+
String s = "aaaaa";
26+
27+
assertEquals(5, UniqueSubsequencesCount.subseqCount(s));
28+
}
29+
}

0 commit comments

Comments
 (0)