Distinct Subsequences Leetcode
2016-08-23 15:54
302 查看
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,
Here is an example:
S =
Return
初始化nums[s.length()+1][t.length() +1] 数组,
nums[i][j]表示s的前i个字符串中选取t的前j个字符,有多少种方案,
如果t为空,从一个字符串里选出来空串,只有一种方案,就是什么都不选。
如果s为空,从空串里选字符串,方案数为0,由于数组不赋值默认就是0,所以不需要再次初始化这部分。
如果s的第i个字符和t的第j个字符不相等,那么从s的前i个字符里选t的前j个字符的方案就等于s的前i -1个字符里选t的前j个字符的方案数。
如果s的第i个字符和t的第j个字符相等,那么从s的前i个字符里选t的前j个字符的方案就等于s的前i -1个字符里选t的前j个字符的方案数加s的前i -1个字符里选t的前j-1个字符的方案数。
或者这样理解,
假设现在只看前两个字符串的前i个和前j个,用长度为j的字符串去匹配长度为i的字符串有几种方法,
那就可以选择是否匹配最后一位,如果不匹配就去找dp[i-1][j],如果匹配就是dp[i-1][j-1], 加在一起就是此事的结果。
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.
初始化nums[s.length()+1][t.length() +1] 数组,
nums[i][j]表示s的前i个字符串中选取t的前j个字符,有多少种方案,
如果t为空,从一个字符串里选出来空串,只有一种方案,就是什么都不选。
如果s为空,从空串里选字符串,方案数为0,由于数组不赋值默认就是0,所以不需要再次初始化这部分。
如果s的第i个字符和t的第j个字符不相等,那么从s的前i个字符里选t的前j个字符的方案就等于s的前i -1个字符里选t的前j个字符的方案数。
如果s的第i个字符和t的第j个字符相等,那么从s的前i个字符里选t的前j个字符的方案就等于s的前i -1个字符里选t的前j个字符的方案数加s的前i -1个字符里选t的前j-1个字符的方案数。
或者这样理解,
假设现在只看前两个字符串的前i个和前j个,用长度为j的字符串去匹配长度为i的字符串有几种方法,
那就可以选择是否匹配最后一位,如果不匹配就去找dp[i-1][j],如果匹配就是dp[i-1][j-1], 加在一起就是此事的结果。
public class Solution { public int numDistinct(String s, String t) { if (s == null || t == null) { return 0; } int[][] nums = new int[s.length() + 1][t.length() + 1]; for (int i = 0; i < s.length() + 1; i++) { nums[i][0] = 1; } for (int i = 1; i < s.length() + 1; i++) { for (int j = 1; j < t.length() + 1; j++) { nums[i][j] = nums[i - 1][j]; if(s.charAt(i - 1) == t.charAt(j -1)) { nums[i][j] += nums[i -1][j - 1]; } } } return nums[s.length()][t.length()]; } }
相关文章推荐
- SQL DISTINCT、GROUP BY
- DataTabel Distinct条件选择
- QBC的distinct查询
- 泛型的Distinct(IEqualityComparer)的用法
- SQL中distinct的用法
- SPOJ 705 New Distinct Substrings
- SQL SELECT DISTINCT 语句
- oracleI基础入门(6)--sql语句-distinct
- oracle去重复记录的方式不用distinct而用groupby
- 目前来看较完美的通用二分法分页存储过程,not in模式,适用于非数值ID,可多字段排序,可以distinct
- 694. Distinct Substrings SPOJ
- 如何解决错误Cannot resolve collation conflict for DISTINCT operation?
- oracle sql 去重复记录不用distinct如何实现
- SQL DISTINCT ON 取消多列重复字段值
- group by,distinct的使用(30万数据测试)
- mysql 去除重复 Select中DISTINCT关键字的用法
- 字段转置count(distinct xxx) 与distinct
- 原来DataTable的Distinct竟如此简单!
- 解析mysql中:单表distinct、多表group by查询去除重复记录
- mysql数据去重复distinct、group by