LeetCode Distinct Subsequences(动态规划)
来源:互联网 发布:艾克里里淘宝店叫什么 编辑:程序博客网 时间:2024/06/06 16:26
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
.
题意:给出两个字符串s,t,求t在s中子串的个数(注意是非连续的)
思路:用dp(i,j)表示字符串t[1..j]在s[1..i]中出现的子串的个数,其状态转移方程为
如果s[i]==t[j],有dp(i,j)=dp(i-1,j-1)+dp(i-1,j)
如果s[i]不等于t[j],有dp(i,j)=dp(i-1,j)
注意初始值为dp[0..len(s)][0] = 1,而dp[0][1..len(t)] = 0
代码如下:
public class Solution{ public int numDistinct(String s, String t) { int len1 = s.length(), len2 = t.length(); int[][] dp = new int[len1 + 1][len2 + 1]; dp[0][0] = 1; for (int i = 0; i < len2; i++) { dp[0][i + 1] = 0; } for (int i = 0; i < len1; i++) { dp[i + 1][0] = 1; } for (int i = 0; i < len1; i++) { for (int j = 0; j < len2; j++) { if (s.charAt(i) == t.charAt(j)) { dp[i + 1][j + 1] = dp[i][j] + dp[i][j + 1]; } else { dp[i + 1][j + 1] = dp[i][j + 1]; } } } return dp[len1][len2]; }}
动态规划的滚动数组实现如下:
public class Solution{ public int numDistinct(String s, String t) { int len1 = s.length(), len2 = t.length(); int[][] dp = new int[2][len2 + 1]; dp[0][0] = 1; for (int i = 0; i <= len1; i++) { for (int j = 0; j <= len2; j++) { if (i == 0 && j > 0) { dp[i & 1][j] = 0; } else if (i > 0 && j == 0) { dp[i & 1][j] = 1; } else if (i > 0 && j > 0) { if (s.charAt(i - 1) == t.charAt(j - 1)) { dp[i & 1][j] = dp[(i - 1) & 1][j] + dp[(i - 1) & 1][j - 1]; } else { dp[i & 1][j] = dp[(i - 1) & 1][j]; } } } } return dp[len1 & 1][len2]; }}
0 0
- LeetCode Distinct Subsequences(动态规划)
- 115.leetcode Distinct Subsequences(hard)[动态规划]
- LeetCode 115. Distinct Subsequences| 动态规划
- LeetCode(115) Distinct Subsequences(动态规划)
- Leetcode Distinct Subsequences 动态规划法活用总结
- Leetcode Distinct Subsequences 动态规划法活用总结
- 10069 - Distinct Subsequences(高精度+动态规划)
- 动态规划——distinct-subsequences
- 115. Distinct Subsequences--动态规划的方法
- 13.11—动态规划—Distinct Subsequences
- 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
- poj 1019 Number Sequence(打表+二分)
- Struts2 入门示例
- Pro Android学习笔记(一四四):触摸屏(3):多点触摸
- UVA 11427 Expect the Expected
- 学习笔记3——32位和64位Linux操作系统的区别及系统识别方法
- LeetCode Distinct Subsequences(动态规划)
- 第二部分:文字录入及身份证校验
- Xcode删除所有的mobileprovision
- python第四天学习记录——装饰器、生成器、内置函数
- https介绍
- LintCode算法题解
- poj2299:Ultra-QuickSort(树状数组+离散化)
- Android相关导图
- Binary 【NOIP2016提高A组模拟8.17】