码迷,mamicode.com
首页 > 编程语言 > 详细

Java for LeetCode 115 Distinct Subsequences【HARD】

时间:2015-05-24 12:51:44      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:

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.

解题思路:

dp问题,弄清递推公式即可,参考Distinct Subsequences@LeetCode ,JAVA实现如下:

	public int numDistinct(String s, String t) {
		if (t.length() == 0)
			return 1;
		int[] dp = new int[t.length() + 1];
		dp[0] = 1;
		for (int i = 0; i < s.length(); i++) {
			int last = 1;
			for (int j = 0; j < t.length(); j++) {
				if (dp[j] == 0)
					break;
				int temp = dp[j + 1];
				if (s.charAt(i) == t.charAt(j))
					dp[j + 1] += last;
				last = temp;
			}
		}
		return dp[t.length()];
	}

 

Java for LeetCode 115 Distinct Subsequences【HARD】

标签:

原文地址:http://www.cnblogs.com/tonyluis/p/4525608.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!