LeetCode-Distinct Subsequences
来源:互联网 发布:开淘宝怎么开 编辑:程序博客网 时间:2024/05/22 05:04
题目: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
.
动态规划,定义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 Distinct Subsequences
- [LeetCode]Distinct Subsequences
- [Leetcode] Distinct Subsequences *
- [leetcode] Distinct Subsequences
- [LeetCode] Distinct Subsequences
- [Leetcode] Distinct Subsequences
- leetcode 111: Distinct Subsequences
- LeetCode Distinct Subsequences
- [leetcode] Distinct Subsequences
- LeetCode - Distinct Subsequences
- Leetcode:Distinct Subsequences
- [LeetCode]Distinct Subsequences
- [LeetCode] Distinct Subsequences
- [Leetcode]Distinct Subsequences
- [leetcode]Distinct Subsequences
- Leetcode: Distinct Subsequences
- Leetcode: Distinct Subsequences
- [leetcode] Distinct Subsequences
- Template Method模式和Strategy模式有何异同
- Split()说明
- C++ MFC combo box和list control控件的使用
- java反射机制详解 及 Method.invoke解释 getMethod
- Ubuntu14.04建立WiFi热点
- LeetCode-Distinct Subsequences
- Ubuntu常见问题解决办法
- 格式化输出年月日和星期
- 好看的小说
- Java中守护线程的总结
- Java学习笔记--JPanel的使用
- phpMyAdmin的pma
- 解决异常:android.os.NetworkOnMainThreadException
- unity3d AudioToolKit 音频管理插件使用方法