115. Distinct Subsequences
/**
* Problem: LeetCode 115 - Distinct Subsequences
* Difficulty: Hard
* Language: Java
* Author: CodeByTushu
*/
class Solution {
public int numDistinct(String s, String t) {
int m = s.length(), n = t.length();
int[][] dp = new int[m + 1][n + 1];
for (int i = 0; i <= m; i++) {
dp[i][0] = 1;
}
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
dp[i][j] = dp[i - 1][j];
if (s.charAt(i - 1) == t.charAt(j - 1)) {
dp[i][j] += dp[i - 1][j - 1];
}
}
}
return dp[m][n];
}
}
"""
Problem: LeetCode 115 - Distinct Subsequences
Difficulty: Hard
Language: Python
Author: CodeByTushu
"""
class Solution:
def numDistinct(self, s: str, t: str) -> int:
m, n = len(s), len(t)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1):
dp[i][0] = 1
for i in range(1, m + 1):
for j in range(1, n + 1):
dp[i][j] = dp[i - 1][j]
if s[i - 1] == t[j - 1]:
dp[i][j] += dp[i - 1][j - 1]
return dp[m][n]
/**
* Problem: LeetCode 115 - Distinct Subsequences
* Difficulty: Hard
* Language: C++
* Author: CodeByTushu
*/
#include <string>
#include <vector>
using namespace std;
/**
* Problem: LeetCode 115 - Distinct Subsequences
* Difficulty: Hard
* Language: C++
* Author: CodeByTushu
*/
class Solution {
public:
int numDistinct(string s, string t) {
int m = s.length(), n = t.length();
vector<vector<unsigned long long>> dp(m + 1, vector<unsigned long long>(n + 1, 0));
for (int i = 0; i <= m; i++) {
dp[i][0] = 1;
}
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
dp[i][j] = dp[i - 1][j];
if (s[i - 1] == t[j - 1]) {
dp[i][j] += dp[i - 1][j - 1];
}
}
}
return static_cast<int>(dp[m][n]);
}
};
/**
* Problem: LeetCode 115 - Distinct Subsequences
* Difficulty: Hard
* Language: JavaScript
* Author: CodeByTushu
*/
var numDistinct = function(s, t) {
const m = s.length, n = t.length;
const dp = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
for (let i = 0; i <= m; i++) {
dp[i][0] = 1;
}
for (let i = 1; i <= m; i++) {
for (let j = 1; j <= n; j++) {
dp[i][j] = dp[i - 1][j];
if (s[i - 1] === t[j - 1]) {
dp[i][j] += dp[i - 1][j - 1];
}
}
}
return dp[m][n];
};
SPACE COMPLEXITY
O(M * N)