LeetCode Distinct Subsequences
来源:互联网 发布:通风管道阻力计算软件 编辑:程序博客网 时间:2024/06/04 01:29
Description:
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
.
Solution:
Assume dp[i][j] represents the number of distinct subsequences from s[1,i] to t[1,j]
Like the edit distance, we should start from empty string(dp[0][i] and dp[i][0])
And it is very simple to come to the idea that
dp[i][0] = 1 s.t. any i
dp[0][i] = 0 s.t. i>=1
Then start the loop
If s[i] != t[j]: dp[i][j] = dp[i-1][j] (1)
Else: dp[i][j] = dp[i-1][j] + dp[i-1][j-1] (2)
(1) s[i] and t[j] does not equal, then the distinct number is equal to dp[i-1][j]
(2) since these two are equal, we can utilize this in two ways: match s[i] and t[j], then we can get dp[i-1][j-1]; do not match s[i] and t[j], then we can get dp[i-1][j]. So for this condition, dp[i][j] = dp[i-1][j-1] + dp[i-1][j].
<span style="font-size:18px;">public class Solution {public int numDistinct(String s, String t) {int n = s.length();int m = t.length();int dp[][] = new int[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;char ch1, ch2;for (int i = 1; i <= n; i++) {ch1 = s.charAt(i - 1);for (int j = 1; j <= m; j++) {ch2 = t.charAt(j - 1);if (ch1 != ch2)dp[i][j] = dp[i - 1][j];else {dp[i][j] = dp[i - 1][j] + dp[i - 1][j - 1];}}}return dp[n][m];}}</span>
- 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
- CKEditor配置属性
- CSS3实现的响应式字体:自适应视图窗口大小的新单位
- 最短路径—Dijkstra算法和Floyd算法
- 关于NoSQL数据库的五大优势与挑战
- MFC多个dll同时操作时导致资源出错问题
- LeetCode Distinct Subsequences
- 反射机制图
- cdh-hadoop-5.4.x pom.xml
- Mac OS X 上搭建LAMP环境(续)
- 修改PE文件.rdata段属性, 使常量区可写
- android studio返回撤销,还原Ctrl+z掉的内容
- OC中常见的错误
- 并发设计中的应用分发问题算法
- Unity3D脚本自动添加tag和Layer