Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

edit - optimized solution to 0115- Distint Subsequence #3658

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
52 changes: 17 additions & 35 deletions java/0115-distinct-subsequences.java
Original file line number Diff line number Diff line change
@@ -1,40 +1,22 @@
// Dynammic Programming - Memoization
// Time Complexity O(s * t) | Space Complexity O(s * t)
class Solution {
import java.util.Arrays;

class Solution {
public int numDistinct(String s, String t) {
int n = s.length() + 1;
int m = t.length() + 1;
int[][] memo = new int[n][m];

for (int[] row : memo) {
Arrays.fill(row, -1);
}

return recursion(s, t, 0, 0, memo);
}

public int recursion(String s, String t, int sIdx, int tIdx, int[][] memo) {
if (memo[sIdx][tIdx] != -1) {
return memo[sIdx][tIdx];
int n = s.length();
int m = t.length();


int[] dp = new int[m + 1];
dp[0] = 1;

for (int i = 0; i < n; i++) {
for (int j = m; j > 0; j--) {
if (s.charAt(i) == t.charAt(j - 1)) {
dp[j] += dp[j - 1];
}
}
}

if (tIdx >= t.length()) {
return 1;
}

if (sIdx >= s.length()) {
return 0;
}

if (t.charAt(tIdx) == s.charAt(sIdx)) {
memo[sIdx][tIdx] =
recursion(s, t, sIdx + 1, tIdx + 1, memo) +
recursion(s, t, sIdx + 1, tIdx, memo);
return memo[sIdx][tIdx];
}

memo[sIdx][tIdx] = recursion(s, t, sIdx + 1, tIdx, memo);
return memo[sIdx][tIdx];

return dp[m];
}
}