我的LeetCode代码仓:https://github.com/617076674/LeetCode
原题链接:https://leetcode-cn.com/problems/distinct-subsequences/description/
题目描述:
知识点:动态规划
思路:动态规划
状态定义:
f(x, y) -------- 记t中[0, x]范围的子串为t',记s中[0, y]范围的子串为s',f(x, y)表示在s'中t'出现的个数。
状态转移:
(1)对于x == 0的情况,
a:当y == 0时,如果s.charAt(0) == t.charAt(0),则f(0, 0) = 1;否则f(0, 0) = 0。
b:当y > 0 时,如果s.charAt(y) == t.charAt(0),f(0, y) = f(0, y - 1) + 1;否则f(0, y) = f(0, y - 1)。
(2)对于x > 0的情况
a:如果x > y,即t'的长度大于s',显然f(x, y) = 0。
b:如果x <= y,
b-1:如果t.charAt(x) == s.charAt(y),则f(x, y) = f(x, y - 1) + f(x - 1, y - 1)
b-2:否则,f(x, y) = f(x, y - 1)。
时间复杂度和空间复杂度均是O(m * n),其中m为t的长度,n为s的长度。
JAVA代码:
class Solution {
public int numDistinct(String s, String t) {
int lenX = t.length();
int lenY = s.length();
if(lenY == 0){
return 0;
}
int[][] dp = new int[lenX][lenY];
if(t.charAt(0) == s.charAt(0)){
dp[0][0] = 1;
}else{
dp[0][0] = 0;
}
for(int i = 1; i < lenY; i++){
if(s.charAt(i) == t.charAt(0)){
dp[0][i] = dp[0][i - 1] + 1;
}else{
dp[0][i] = dp[0][i - 1];
}
}
for(int i = 1; i < lenX; i++){
for(int j = 0; j < lenY; j++){
if(i > j){
dp[i][j] = 0;
}else{
if(t.charAt(i) == s.charAt(j)){
dp[i][j] = dp[i][j - 1] + dp[i - 1][j - 1];
}else{
dp[i][j] = dp[i][j - 1];
}
}
}
}
return dp[lenX - 1][lenY - 1];
}
}
LeetCode解题报告: