LeetCode: Distinct Subsequences 解题报告
2014-12-31 18:21
405 查看
Distinct Subsequences
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 5: improved recursion version without memory. public int numDistinct(String S, String T) { if (S == null || T == null) { return 0; } return rec5(S, T, 0, 0); } public int rec5(String S, String T, int indexS, int indexT) { int lenS = S.length(); int lenT = T.length(); // base case: if (indexT >= lenT) { // T is empty. return 1; } if (indexS >= lenS) { // S is empty but T is not empty. return 0; } int sum = 0; for (int i = indexS; i < lenS; i++) { // choose which character in S to choose as the first character of T. if (S.charAt(i) == T.charAt(indexT)) { sum += rec5(S, T, i + 1, indexT + 1); } } return sum; }
View Code
总结:
大家可以在SOLUTION 1和SOLUTION 4两个选择里用一个就好啦。http://blog.csdn.net/fightforyourdream/article/details/17346385?reload#comments
这道题可以作为两个字符串DP的典型:
两个字符串:
先创建二维数组存放答案,如解法数量。注意二维数组的长度要比原来字符串长度+1,因为要考虑第一个位置是空字符串。
然后考虑dp[i][j]和dp[i-1][j],dp[i][j-1],dp[i-1][j-1]的关系,如何通过判断S.charAt(i)和T.charAt(j)的是否相等来看看如果移除了最后两个字符,能不能把问题转化到子问题。
最后问题的答案就是dp[S.length()][T.length()]
还有就是要注意通过填表来找规律。
GITHUB:
https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/dp/NumDistinct.java相关文章推荐
- [leetcode] 285. Inorder Successor in BST 解题报告
- [Leetcode] 108. Convert Sorted Array to Binary Search Tree 解题报告
- [Leetcode] 82. Remove Duplicates from Sorted List II 解题报告
- [leetcode] 352. Data Stream as Disjoint Intervals 解题报告
- [Leetcode] 191. Number of 1 Bits 解题报告
- [leetcode]76. Minimum Window Substring@Java解题报告
- 【LeetCode】156.Binary Tree Upside Down(Medium)(加锁题)解题报告
- LeetCode: Next Permutation 解题报告
- leetCode解题报告之Copy List with Random Pointer
- 【LeetCode】744. Find Smallest Letter Greater Than Target 解题报告
- LeetCode 216. Combination Sum III 解题报告
- [Leetcode] 313. Super Ugly Number 解题报告
- [Leetcode] 319. Bulb Switcher 解题报告
- [leetcode] 163. Missing Ranges 解题报告
- [Leetcode] 119. Pascal's Triangle II 解题报告
- 【LeetCode】 Add Digits 解题报告
- leetcode 40. Combination Sum II 解题报告
- LeetCode解题报告--Search Insert Position
- Leetcode: LRU Cache 解题报告
- [LeetCode]Nth Highest Salary,解题报告