LeetCode-Distinct Subsequences

题目: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 of "ABCDE" while "AEC" is not).

Here is an example:
S = "rabbbit"T = "rabbit"

Return 3.

分析:(参考地址: http://blog.csdn.net/worldwindjp/article/details/19770281)

动态规划,定义f[i][j]为字符串S变换到T的变换方法。
(1) 如果S[i]==T[j],那么f[i][j] = f[i-1][j-1] + f[i-1][j]。意思是:如果当前S[i]==T[j],那么当前这个字母即可以保留也可以抛弃,所以变换方法等 于保留这个字母的变换方法加上不用这个字母的变换方法。
(2) 如果S[i]!=T[i],那么f[i][j] = f[i-1][j],意思是如果当前字符不等,那么就只能抛弃当前这个字符。
递归公式中用到的f[0][0] = 1,f[i][0] = 0(把任意一个字符串变换为一个空串只有一个方法)

源码:Java版本
算法分析:时间复杂度O(m*n),空间复杂度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];
    }
}

上述代码的空间复杂度O(m*n)可以优化,使用滚动数组,空间复杂度可以降为O(n)

算法分析:时间复杂度O(m*n),空间复杂度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];
    }
}

你可能感兴趣的:(LeetCode)