首页 > 代码库 > Distinct Subsequences
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). Have you met this question in a real interview? Yes Example Given S = "rabbbit", T = "rabbit", return 3. Challenge Do it in O(n2) time and O(n) memory. O(n2) memory is also acceptable if you do not know how to optimize memory.
动归: 状态的加法
分完情况后根据遍历到的点的S的当前字母匹不匹配T的当前字母的问题来进行状态转移:
public int numDistinct(String S, String T) { // write your code here //state int m = S.length(); int n = T.length(); // initialize int[][] f = new int[m + 1][n + 1]; for (int i = 0; i <= m; i++) { f[i][0]= 1; } for (int j = 1; j <= n; j++) { f[0][j] = 0; } //function for (int i = 1; i<= m; i++) { for (int j = 1; j <= n; j++) { if (S.charAt(i - 1) == T.charAt(j - 1)) { f[i][j] = f[i- 1][j - 1] + f[i - 1][j]; } else { f[i][j] = f[i - 1][j]; } } } return f[m][n]; }
一维数组. 逆序以保证 f[i][j] = f[i- 1][j - 1] + f[i - 1][j]; 加的是上一层的i- 1
public class Solution { public int numDistinct(String S, String T) { if (S==null || T==null || S.length() < T.length()) return 0; int[] res = new int[T.length()+1]; res[0] = 1; for (int i=1; i<=S.length(); i++) { for (int j=T.length(); j>0; j--) { res[j] = S.charAt(i-1) == T.charAt(j-1)? res[j-1] + res[j] : res[j]; } } return res[T.length()]; } }
Distinct Subsequences
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。