115.leetcode Distinct Subsequences(hard)[动态规划]
2016-08-04 20:17
295 查看
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,
a subsequence of
not).
Here is an example:
S =
Return
题目的含义是要求T成为S的子串的形成方式的个数。组成动态规划状态数组L[t.length()+1][s.length()+1].
class Solution {
public:
int numDistinct(string s, string t) {
if(s.length()<t.length()||t.length()==0||s.length()==0) return 0;
int n = s.length(),m = t.length();
int L[m+1][n+1];
for(int i=0;i<=m;i++)
for(int j=0;j<=n;j++)
L[i][j] = 0;
for(int j=0;j<=n;j++)
L[0][j] = 1;
for(int i=1;i<=m;i++)
{
for(int j = i; j<=n;j++)
{
if(s[j-1] == t[i-1])
{
L[i][j] = L[i-1][j-1]+L[i][j-1];
}else
L[i][j] = L[i][j-1];
}
}
return L[m]
;
}
};
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.
题目的含义是要求T成为S的子串的形成方式的个数。组成动态规划状态数组L[t.length()+1][s.length()+1].
class Solution {
public:
int numDistinct(string s, string t) {
if(s.length()<t.length()||t.length()==0||s.length()==0) return 0;
int n = s.length(),m = t.length();
int L[m+1][n+1];
for(int i=0;i<=m;i++)
for(int j=0;j<=n;j++)
L[i][j] = 0;
for(int j=0;j<=n;j++)
L[0][j] = 1;
for(int i=1;i<=m;i++)
{
for(int j = i; j<=n;j++)
{
if(s[j-1] == t[i-1])
{
L[i][j] = L[i-1][j-1]+L[i][j-1];
}else
L[i][j] = L[i][j-1];
}
}
return L[m]
;
}
};
相关文章推荐
- 87. Scramble String *HARD* 动态规划
- 629. K Inverse Pairs【Hard】 动态规划
- AtCoder Regular Contest 066 E - Addition and Subtraction Hard 动态规划
- 514. Freedom Trail 【Hard】 动态规划
- 312. Burst Balloons 难度:hard 类别:分治、动态规划
- 689. Maximum Sum of 3 Non-Overlapping Subarrays 【Hard】 动态规划
- (九)记录结果再利用的“动态规划”
- What Is a Hard Inquiry?(Fico信用查询之“硬查询”)
- 关于git reset --hard导致文件丢失的血的教训
- 动态规划0-1背包问题
- 动态规划、记忆化搜索、Dijkstra算法的总结
- 动态规划(17)
- 分治法、动态规划、贪心法比较
- 014-背包问题-动态规划-《算法设计技巧与分析》M.H.A学习笔记
- 动态规划——免费馅饼
- 五类常见算法小记 (递归与分治,动态规划,贪心,回溯,分支界限法)
- HDU 5534 Partial Tree(动态规划)
- DAG 动态规划 -- 硬币问题
- 《背包问题》 动态规划
- 贪心法__动态规划-数塔问题