[Leetcode] 115. Distinct Subsequences 解题报告
来源:互联网 发布:听打测试软件 编辑:程序博客网 时间:2024/05/17 07:13
题目:
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
.
思路:
刚刚开始想到的是回溯法,但是实现之后发现过不了大数据。所以还是采用处理字符串匹配问题的神器:动态规划。可以用一个二维数组dp[i][j]表示S的前i个字符所包含的子字符串和T的前j个字符的匹配个数。此时可以分为两种情况:
1)s[i] != t[j],那么dp[i][j] = dp[i-1][j],即如果当前的字符串不相等,则dp[i][j]的值为s抛去第j-1个字符之后,所包含的子串匹配个数。
2)s[i] == t[j],那么dp[i][j]就可以继承dp[i-1][j-1]的值,再加上没有s[i-1]这个字符的值,即dp[i][j] = dp[i-1][j-1] + dp[i-1][j]。更简单的理解可以是:按照t[j-1]是和s[i-1]匹配还是和s[i-1]之前的字符匹配,可以将结果分为两类,即dp[i-1][j-1]和dp[i-1][j]。
另外初始状态dp[i][0] = 1,可以理解为空串是任意字符串的子串;而dp[0][j] = 0,可以理解为空串不能包含任意一个非空字符串。
代码:
class Solution {public: int numDistinct(string s, string t) { int s_size = s.length(); int t_size = t.length(); if(t_size > s_size || s_size == 0 || t_size == 0) { return 0; } vector<vector<int>> dp(s_size + 1, vector<int>(t_size + 1, 0)); for(int i = 0; i <= s_size; ++i) { for(int j = 0; j <= t_size; ++j) { if (j == 0) { // t is an empty string dp[i][j] = 1; } else if (i == 0) { // s is an empty string dp[i][j] = 0; } else { if(s[i-1] == t[j-1]) { dp[i][j] += dp[i-1][j-1]; } dp[i][j] += dp[i-1][j]; // discard the last character of s } } } return dp[s_size][t_size]; }};
- [leetcode] 115. Distinct Subsequences 解题报告
- [Leetcode] 115. Distinct Subsequences 解题报告
- Leetcode Distinct Subsequences 解题报告
- [LeetCode]Distinct Subsequences,解题报告
- 【LeetCode】Distinct Subsequences 解题报告
- [Leetcode] Distinct Subsequences 解题报告
- Leetcode 115. Distinct Subsequences 计算子串 解题报告
- Distinct Subsequences 解题报告
- leetCode Distinct Subsequences 解题分享
- leetcode解题笔记-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
- int 与 byte 的强制类型转换
- Android Arm Inline Hook
- apache CentOS Permission denied: AH00072
- <Android 开源库> PhotoPicker 从头到脚
- spring mvc实战系列教程(5)--将对象转换为XML输出
- [Leetcode] 115. Distinct Subsequences 解题报告
- IDEA破解
- 一个MySQL表真的最多只能够有24个字段吗?反正我不信
- 数据库笔记 4
- 欢迎使用CSDN-markdown编辑器
- 局域网计算机间进行通信都经历了什么
- java并发编程之volatile关键字解析
- OpenCV学习之编译OpenCV
- 下载文件