第42题 Distinct Subsequences
来源:互联网 发布:java递归算法方程式 编辑:程序博客网 时间:2024/06/05 20:31
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
.
Code in Java:
public class Solution { public int numDistinct(String S, String T) { //count the number of ways to convert S to T by deleting some characters in S. if(S.length()==0&&T.length()==0) return 0; if(S.length()<T.length()) return 0; int lenS = S.length(), lenT = T.length(); //Use opj[i][j] to represent the number of ways to convert S[0...i-1] to T[0...j-1] //So opj[lenS][lenT] is the total number of ways to convert S to T int[][] opj = new int[lenS+1][lenT+1]; //opj[i][0] represents the number of ways to convert S[0...i-1] to an empty string //so for any string, there is only one ways, which is deleting all the characters for(int i=0; i<lenS+1; i++) opj[i][0]=1; //There are two possibilities when computing opj[i][j] from S[0...i-1] to T[0...j-1]: //if S[i-1]==T[j-1], we can obtain opj[i][j] by either remaining or deleting S[i-1] // if remain S[i-1]: opj[i][j]=opj[i-1][j-1] // the number of ways from S[0...i-1] to T[0...j-1]=the number of ways // from S[0...i-2] to T[0...j-2] // if delete S[i-1]: opj[i][j]=opj[i-1][j] // the number of ways from S[0...i-1] to T[0...j-1]=the number of ways // from S[0...i-2] to T[0...j-1] //if S[i-1]!=T[j-1], there is only one way to obtain opj[i][j], wo we have // opj[i][j] = opj[i-1][j] // the number of ways from S[0...i-1] to T[0...j-1]=the nubmer of ways from // S[0...i-2] to T[0...j-1] for(int i=1; i<lenS+1; i++){ for(int j=1; j<lenT+1&&j<=i; j++){ opj[i][j] = S.charAt(i-1)==T.charAt(j-1)?opj[i-1][j-1]:0; if(i-1>=j) opj[i][j]+= opj[i-1][j]; } } return opj[lenS][lenT]; }}
0 0
- 第42题 Distinct Subsequences
- Distinct Subsequences
- Distinct Subsequences
- Distinct Subsequences
- Distinct Subsequences
- Distinct Subsequences
- Distinct Subsequences
- Distinct Subsequences
- Distinct Subsequences
- Distinct Subsequences
- Distinct Subsequences
- Distinct Subsequences
- Distinct Subsequences
- Distinct Subsequences
- Distinct Subsequences
- Distinct Subsequences
- Distinct Subsequences
- Distinct Subsequences
- git使用技巧(原文:git深度使用经验总结)
- Excel Sheet Column Number
- iOS 平台项目接入新浪微博 SDK 的坑
- iOS开发ASIHttpRequest库简介、配置和安装【1】
- Android Studio 快捷键
- 第42题 Distinct Subsequences
- 【PHP】curl 提交数据
- ASPX前台调用后台带参数的方法
- [原创] 《刀塔传奇》研究报告
- Oracle 创建表空间和用户
- spark-streaming连接flume时报错org.jboss.netty.channel.ChannelException: Failed to bind to: /IP:PORT
- Linux下进程管理一
- unity--鼠标放上显示物体信息和物体高光效果
- lm317扩流电路 (全集)