LintCode -- 不同的子序列
来源:互联网 发布:潘石屹三段婚姻知乎 编辑:程序博客网 时间:2024/05/19 02:20
LintCode -- distinct-subsequences(不同的子序列)
原题链接:http://www.lintcode.com/zh-cn/problem/distinct-subsequences/
给出字符串S和字符串T,计算S的不同的子序列中T出现的个数。
子序列字符串是原始字符串通过删除一些(或零个)产生的一个新的字符串,并且对剩下的字符的相对位置没有影响。(比如,“ACE”是“ABCDE”的子序列字符串,而“AEC”不是)。
样例
代码(C++、Java、Python):给出S = "rabbbit", T = "rabbit"
返回 3
分析:
dp[ i ][ j ] 表示 T 有 j 个字符,S有 i 个字符时不同子序列个数。
递归式 if (T[ i ] == S[ j ]) dp[ i ][ j ] = dp[ i ][ j-1 ] + dp[ i-1 ][ j-1 ]
else dp[ i ][ j ] = dp[ i ][ j-1 ]
**** 时间复杂度 O(n*m), 空间复杂度 O(m) ****
<span style="font-size:18px;">class Solution {public: /** * @param S, T: Two string. * @return: Count the number of distinct subsequences */ int numDistinct(string &S, string &T) { // write your code here int n = S.size(); int m = T.size(); int dp[m+1][2]; memset(dp, 0, sizeof(dp)); for (int j = 0; j < 2; j++) dp[0][j] = 1; for (int j = 1; j < n+1; j++) for (int i = 1; i < m+1; i++){ dp[i][j%2] = dp[i][(j-1)%2]; if (T[i-1] == S[j-1]) dp[i][j%2] += dp[i-1][(j-1)%2]; } return dp[m][n%2]; }};</span>
<span style="font-size:18px;">public class Solution { /** * @param S, T: Two string. * @return: Count the number of distinct subsequences */ public int numDistinct(String S, String T) { // write your code here int n = S.length(); int m = T.length(); int [][] dp = new int [m+1][2]; for (int j = 0; j < 2; j++) dp[0][j] = 1; for (int j = 1; j < n+1; j++) for (int i = 1; i < m+1; i++){ dp[i][j%2] = dp[i][(j-1)%2]; if (T.charAt(i-1) == S.charAt(j-1)) dp[i][j%2] += dp[i-1][(j-1)%2]; } return dp[m][n%2]; }}</span>
<span style="font-size:18px;">class Solution: # @param S, T: Two string. # @return: Count the number of distinct subsequences def numDistinct(self, S, T): # write your code here n = len(S) m = len(T) dp = [[0 for j in range(2)] for i in range(m+1)] for j in range(2): dp[0][j] = 1 for j in range(1, n+1): for i in range(1, m+1): dp[i][j%2] = dp[i][(j-1)%2] if T[i-1] == S[j-1]: dp[i][j%2] += dp[i-1][(j-1)%2] return dp[m][n%2]</span>
0 0
- LintCode-不同的子序列
- LintCode -- 不同的子序列
- LintCode 不同的子序列
- 不同的子序列-LintCode
- lintcode--不同的子序列
- lintcode之不同子序列数 + 序列II
- 不同的子序列
- 不同的子序列
- 不同的子序列
- 不同的子序列
- LintCode 带重复元素的子序列
- 题目:不同的子序列
- LintCode-乘积最大子序列
- lintcode-最长连续子序列
- LintCode -- 乘积最大子序列
- LintCode : 最长公共子序列
- lintcode- 乘积最大子序列
- LintCode:乘积最大子序列
- 利用HttpOnly来防御xss攻击
- [iOS开发项目-4] 汤姆猫(只包含动作,没有发声功能)
- css过渡和动画初学
- 安全cookie登录状态设计方案
- 使用VirtualBox + Vagrant打造属于自己的开发环境1
- LintCode -- 不同的子序列
- HDU 4293 Groups(dp)
- 优化LINUX内核阻挡SYN洪水攻击
- c++设计模式-----observer(观察者模式)
- apache双向HTTPS SSL认证配置
- GitHub入门与实践一
- OJ学习笔记2
- [九度OnlineJudge][剑指Offer]题目1387:斐波那契数列
- oracle交流趣事--主机名变更在跑某报告信息时变更的小细节