[LeetCode] 115. Distinct Subsequences
来源:互联网 发布:.net域名 编辑:程序博客网 时间:2024/06/05 15:06
难度等级:hard
题目:
Given a string S and a string T, count the number of distinct subsequences of S which equals T.
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.
题解:又是一道dp问题。
状态定义:dp[i][j]代表s[0~i-1]中T[0~j-1]不同子串的个数。
递推关系式:S[i-1]!= T[j-1]: DP[i][j] = DP[i-1][j] (不选择S中的s[i-1]字符)
S[i-1]==T[j-1]: DP[i][j] = DP[i-1][j-1](选择S中的s[i-1]字符) + DP[i-1][j]
初始状态:第0列:DP[i][0] = 1,第0行:DP[0][j] = 0
代码:
class Solution {
public:
int numDistinct(string S, string T) {
int n=S.size();
int m=T.size();
int dp[n+1][m+1];
for(int i=0;i<=n;i++)
dp[i][0]=1;
for(int j=1;j<=m;j++)
dp[0][j]=0;
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++){
if(S[i-1]==T[j-1])
dp[i][j]=dp[i-1][j]+dp[i-1][j-1];
else
dp[i][j]=dp[i-1][j];
}
return dp[n][m];
}
};
public:
int numDistinct(string S, string T) {
int n=S.size();
int m=T.size();
int dp[n+1][m+1];
for(int i=0;i<=n;i++)
dp[i][0]=1;
for(int j=1;j<=m;j++)
dp[0][j]=0;
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++){
if(S[i-1]==T[j-1])
dp[i][j]=dp[i-1][j]+dp[i-1][j-1];
else
dp[i][j]=dp[i-1][j];
}
return dp[n][m];
}
};
阅读全文
0 0
- LeetCode 115. Distinct Subsequences
- [Leetcode] 115. Distinct Subsequences
- [leetcode] 115.Distinct Subsequences
- [leetcode] 115.Distinct Subsequences
- Leetcode 115. Distinct Subsequences
- 【LeetCode】115. Distinct Subsequences
- LeetCode 115. Distinct Subsequences
- [leetcode]115. Distinct Subsequences
- LeetCode-115.Distinct Subsequences
- [LeetCode] 115. Distinct Subsequences
- LeetCode 115. Distinct Subsequences
- leetcode-115. Distinct Subsequences
- leetcode-115. Distinct Subsequences
- [LeetCode]115. Distinct Subsequences
- 【Leetcode】115. Distinct Subsequences
- [LeetCode] 115. Distinct Subsequences
- leetcode:115. Distinct Subsequences
- LeetCode 115. Distinct Subsequences
- Node.js + MongoDB 后端学习笔记
- TCP半关闭状态
- 面试题19 :二叉树的镜像
- android之 Activity跳转出现闪屏
- 实用shell脚本命令记录
- [LeetCode] 115. Distinct Subsequences
- 安卓添加应用栏的菜单键(三个点)
- 解决 centos 启动 tomcat 巨慢的问题
- 360浏览器使用兼容模式网页错乱
- 对象关系映射(ORM)简单看懂
- WIN7 双击计算机 无法打开
- java基础知识
- 一个完整页面应该包含的三个部分。加载中加载完都有不同的特效
- ES6的块级作用域--读书笔记