Repository: TheAlgorithms/Java
Pull request #5586 (2024-10-05 16:18:13)

feat : new dp algo added `UniqueSubsequenceCount.java`
<!--
Thank you for your contribution!
In order to reduce the number of notifications sent to the maintainers, please:
- create your PR as draft, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests#draft-pull-requests,
- make sure that all of the CI checks pass,
- mark your PR as ready for review, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/changing-the-stage-of-a-pull-request#marking-a-pull-request-as-ready-for-review
-->

<!-- For completed items, change [ ] to [x] -->

- [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Java/blob/master/CONTRIBUTING.md).
- [x] This pull request is all my own work -- I have not plagiarized it.
- [x] All filenames are in PascalCase.
- [x] All functions and variable names follow Java naming conventions.
- [x] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations.
- [x] All new code is formatted with `clang-format -i --style=file path/to/your/file.java`

codecov-commenter: ## [Codecov](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5586?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) Report
Attention: Patch coverage is `89.47368%` with `2 lines` in your changes missing coverage. Please review.
> Project coverage is 54.59%. Comparing base [(`f34fe4d`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/f34fe4d8408ac35cef900cfae022ffadfc007ea3?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) to head [(`c7c3d8b`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/c7c3d8be6cf70eb5cc0a71d23a7cbc927465e01a?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).

| [Files with missing lines](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5586?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) | Patch % | Lines |
|---|---|---|
| [...ms/dynamicprogramming/UniqueSubsequencesCount.java](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5586?src=pr&el=tree&filepath=src%2Fmain%2Fjava%2Fcom%2Fthealgorithms%2Fdynamicprogramming%2FUniqueSubsequencesCount.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms#diff-c3JjL21haW4vamF2YS9jb20vdGhlYWxnb3JpdGhtcy9keW5hbWljcHJvZ3JhbW1pbmcvVW5pcXVlU3Vic2VxdWVuY2VzQ291bnQuamF2YQ==) | 89.47% | [2 Missing :warning: ](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5586?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) |

<details><summary>Additional details and impacted files</summary>


```diff
@@             Coverage Diff              @@
##             master    #5586      +/-   ##
============================================
+ Coverage     54.56%   54.59%   +0.03%     
- Complexity     3413     3419       +6     
============================================
  Files           535      536       +1     
  Lines         15383    15402      +19     
  Branches       2935     2939       +4     
============================================
+ Hits           8393     8409      +16     
- Misses         6637     6639       +2     
- Partials        353      354       +1     
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5586?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).   
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).

Tuhinm2002: @siriak @alxkm  Added new algo in dp. Please review it
Tuhinm2002: @alxkm hey check the changes and review it
Tuhinm2002: @alxkm check the new code for review

Patch:
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/UniqueSubsequencesCount.java b/src/main/java/com/thealgorithms/dynamicprogramming/UniqueSubsequencesCount.java
new file mode 100755
index 00000000..8c7ea617
--- /dev/null
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/UniqueSubsequencesCount.java
@@ -0,0 +1,98 @@
+package com.thealgorithms.dynamicprogramming;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * Utility class to find the number of unique subsequences that can be
+ * produced from a given string.
+ *
+ * <p> This class contains static methods to compute the unique subsequence count
+ * using dynamic programming and recursion. It ensures that duplicate characters
+ * are not counted multiple times in the subsequences.</p>
+ *
+ * <p> Author: https://github.com/Tuhinm2002 </p>
+ */
+public final class UniqueSubsequencesCount {
+
+    /**
+     * Private constructor to prevent instantiation of this utility class.
+     * This class should only be used in a static context.
+     *
+     * @throws UnsupportedOperationException if attempted to instantiate.
+     */
+    private UniqueSubsequencesCount() {
+        throw new UnsupportedOperationException("Utility class");
+    }
+
+    /**
+     * Finds the number of unique subsequences that can be generated from
+     * the given string.
+     *
+     * <p> This method initializes a dynamic programming (DP) array and invokes
+     * the recursive helper function to compute the subsequence count.</p>
+     *
+     * @param str the input string from which subsequences are generated
+     * @return the total count of unique subsequences
+     */
+    public static int countSubseq(String str) {
+
+        // DP array initialized to store intermediate results
+        int[] dp = new int[str.length() + 1];
+        Arrays.fill(dp, -1);
+
+        // Calls the recursive function to compute the result
+        return countSubsequences(str, 0, dp);
+    }
+
+    /**
+     * Recursive helper function to count the number of unique subsequences
+     * starting from the given index.
+     *
+     * <p> Uses a HashSet to avoid counting duplicate characters within
+     * a single subsequence.</p>
+     *
+     * @param st the input string
+     * @param idx the current index from which to calculate subsequences
+     * @param dp dynamic programming array used to memoize results
+     * @return the total number of unique subsequences starting from the
+     *         current index
+     */
+    public static int countSubsequences(String st, int idx, int[] dp) {
+
+        // Base case: when index exceeds the string length
+        if (idx >= st.length()) {
+            return 0;
+        }
+
+        // If result is already calculated, return the memoized value
+        if (dp[idx] != -1) {
+            return dp[idx];
+        }
+
+        // Set to store characters to avoid duplicates
+        Set<Character> set = new HashSet<>();
+
+        int res = 0;
+
+        // Iterate over the string starting from current index
+        for (int j = idx; j < st.length(); j++) {
+
+            // If character is already in the set, skip it
+            if (set.contains(st.charAt(j))) {
+                continue;
+            }
+
+            // Add character to set and recursively calculate subsequences
+            set.add(st.charAt(j));
+
+            // 1 for the current subsequence + recursive call for the rest of the string
+            res = 1 + countSubsequences(st, j + 1, dp) + res;
+        }
+
+        // Memoize the result
+        dp[idx] = res;
+        return dp[idx];
+    }
+}


Test patch:
diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/UniqueSubsequencesCountTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/UniqueSubsequencesCountTest.java
new file mode 100755
index 00000000..049804f5
--- /dev/null
+++ b/src/test/java/com/thealgorithms/dynamicprogramming/UniqueSubsequencesCountTest.java
@@ -0,0 +1,15 @@
+package com.thealgorithms.dynamicprogramming;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+
+public class UniqueSubsequencesCountTest {
+
+    @ParameterizedTest
+    @CsvSource({"abc, 7", "abcdashgdhas, 3592", "a, 1", "'a b', 7", "a1b2, 15", "AaBb, 15", "abab, 11"})
+    void subseqCountParameterizedTest(String input, int expected) {
+        assertEquals(expected, UniqueSubsequencesCount.countSubseq(input));
+    }
+}