LeetCode-Distinct Subsequences, leetcode-distinct
Title: https://oj.leetcode.com/problems/distinct-subsequences/
Given a string S and a string T, count the number of distinct subsequences of T in S.
A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie,"ACE"
Is a subsequence"ABCDE"
While"AEC"
Is not ).
Here is an example:
S ="rabbbit"
, T ="rabbit"
Return3
.
Analysis: (reference address: http://blog.csdn.net/worldwindjp/article/details/19770281)
For dynamic planning, define f [I] [j] as the transformation method from string S to T.
(1) If S [I] = T [j], then f [I] [j] = f [I-1] [J-1] + f [I-1] [j]. If the current S [I] = T [j], the current letter can be retained or discarded, therefore, the conversion method is equal to the conversion method for retaining the letter plus the conversion method without the letter.
(2) If S [I]! = T [I], then f [I] [j] = f [I-1] [j], meaning that if the current character is not equal, then only the current character can be discarded.
F [0] [0] = 1, f [I] [0] = 0 in the recursive formula (there is only one method to convert any string into an empty string)
Source code: Java version
Algorithm Analysis: time complexity O (m * n) and space complexity O (m * n)
public class Solution { public int numDistinct(String S, String T) { int m=S.length(); int n=T.length(); int[][] f=new int[m+1][n+1]; for(int i=0;i<m+1;i++) { f[i][0]=1; } for(int i=1;i<m+1;i++) { for(int j=1;j<n+1;j++) { if(S.charAt(i-1)!=T.charAt(j-1)) { f[i][j]=f[i-1][j]; }else { f[i][j]=f[i-1][j-1]+f[i-1][j]; } } } return f[m][n]; }}
The space complexity O (m * n) of the code above can be optimized. Using a rolling array, the space complexity can be reduced to O (n)
Algorithm Analysis: time complexity O (m * n) and space complexity O (n)
public class Solution { public int numDistinct(String S, String T) { int m=S.length(); int n=T.length(); int[] f=new int[n+1]; f[0]=1; for(int i=1;i<m+1;i++) { for(int j=n;j>=1;j--) { if(S.charAt(i-1)==T.charAt(j-1)) { f[j]+=f[j-1]; } } } return f[n]; }}