# Distinct Subsequences@LeetCode

## Distinct Subsequences

• `S.charAt(i - 1) == T.charAt(j - )`，则`match[[i][j] = match[i - 1][j - 1] + match[i - 1][j]`
• `S.charAt(i - 1) != T.charAt(j - 1)`，则`match[i][j] = match[i - 1][j]`

````java````public class Solution {
public int numDistinct(String S, String T) {
if (T.length() == 0) return 1;
int rows = S.length() + 1, cols = T.length() + 1;
int[][] dp = new int[rows][cols];
dp[0][0] = 1;
for (int i = 1; i < rows; i++) {
dp[i][0] = 1;
for (int j = 1; j < cols; j++) {
if (S.charAt(i - 1) == T.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j];
} else {
dp[i][j] = dp[i - 1][j];
}
}
}
return dp[rows - 1][cols - 1];
}
}
``````

````java````public class Solution {
public int numDistinct(String S, String T) {
if (T.length() == 0) {
return 1;
}
int[] dp = new int[T.length() + 1];
dp[0] = 1;
for (int i = 0; i < S.length(); i++) {
int hold = 1;
for (int j = 1; j < dp.length; j++) {
if (dp[j - 1] == 0)
break;
int h = dp[j];
if (S.charAt(i) == T.charAt(j - 1)) {
dp[j] = hold + dp[j];
}
hold = h;
}
}
return dp[dp.length - 1];
}
}
``````

1.1k 声望
63 粉丝
0 条评论