Leetcode-distinct-subsequences
来源:互联网 发布:java自学书籍推荐书目 编辑:程序博客网 时间:2024/06/13 18:39
题目描述
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"
Return3.
题目意思:只能通过删除字符的形式将S变为T,求有多少种方法?
典型动态规划题目。
递推关系是:dp[i][j]表示0~i的String变化为0~j的String的方法数。
dp[x][0]表示S变为空串就只有一种方法。
如果S的第i个位置和T的第j个位置不同,那么该位置元素必然要删除,那么dp[i][j] = dp[i-1][j]
如果S的第i个位置和T的第j个位置相同,可以删,也可不删,那么dp[i][j] = dp[i-1][j-1] + dp[i-1][j]
最终dp[S.length()][T.length()]就是最终的答案。
public class Solution { public int numDistinct(String S, String T) { if(S == null || S.length() == 0) return 0; int[][] dp = new int[S.length()+1][T.length()+1]; dp[0][0] = 1; for(int i=1; i<S.length()+1; i++) { dp[i][0] = 1; } for(int i=1; i<=S.length(); i++) { for(int j=1; j<=T.length(); j++) { if(S.charAt(i-1) == T.charAt(j-1)){ dp[i][j] = dp[i-1][j]+dp[i-1][j-1];; }else{ dp[i][j] = dp[i-1][j]; } } } return dp[S.length()][T.length()]; }}
0 0
- 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
- BGRABitmap图像操作8:彩色纹理
- 【opencv练习19 - 图像添加边界】
- Counting Bits——Difficulty:Medium
- 地址传递用法
- android Toast大全(五种情形)建立属于你自己的Toast
- Leetcode-distinct-subsequences
- java。socket编程入门
- 我要搞程序
- C++ operator关键字(重载操作符)
- Android性能优化之Bitmap的内存优化
- Github上传本地项目
- Coursera机器学习 week9 assignment
- Ruby Programming
- 安卓IPC之aidl使用(一)--aidl常见使用