Leetcode 115 Distinct Subsequences

题目:

Given a string S and a string T, count the number of distinct subsequences of S which equals T.

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).

Example 1:

Input: S = "rabbbit", T = "rabbit"
Output: 3
Explanation:

As shown below, there are 3 ways you can generate "rabbit" from S.
(The caret symbol ^ means the chosen letters)

rabbbit
^^^^ ^^
rabbbit
^^ ^^^^
rabbbit
^^^ ^^^

这道题关键也是图表,我想到了以前吃的亏,s1和s2都需要用到,于是图标是这个样子:

先初始化这样:


因为列j必须>=行i


如果想等则是由他的斜上角和他的前一个的和,dp[i][j]表示,s[0----j]中有多少个t[0-----i]的子字符串。

具体的代码如下,当然应该还是可以改进的:

package test;
//也可以压缩空间
public class LC115Try1
{
	public int numDistinct(String s, String t)
	{
		int l1 = s.length();
		int l2 = t.length();
		if (l2 > l1)
		{
			return 0;
		}
		if (l2 == 0)
		{
			return 1;
		}
		char[] c1 = s.toCharArray();
		char[] c2 = t.toCharArray();
		int[][] dp = new int[l2][l1];
		if (c1[0] == c2[0])
		{
			dp[0][0] = 1;
		}
		for (int j = 1; j < l1; j++)
		{
			if (c1[j] == c2[0])
			{

				dp[0][j] = dp[0][j - 1] + 1;

			}
			else
			{
				dp[0][j] = dp[0][j - 1];
			}
		}
		for (int i = 1; i < l2; i++)
		{
			if (c1[i] == c2[i] && dp[i - 1][i] > 0)
			{
				dp[i][i] = dp[i - 1][i - 1];
			}
			for (int j = i + 1; j < l1; j++)
			{
				if (c1[j] == c2[i] && dp[i - 1][j - 1] > 0)
				{
					dp[i][j] = dp[i - 1][j - 1] + dp[i][j - 1];
				}
				else
				{
					dp[i][j] = dp[i][j - 1];
				}
			}
		}

		return dp[l2 - 1][l1 - 1];

	}

	public static void main(String[] args)
	{
		LC115Try1 t = new LC115Try1();
		System.out.println(t.numDistinct("hgghghhh", "  "));
	}

}

知道这个基本原理:也可以利用空间压缩,比如还可以利用如下的代码:

package test;

public class LC115Try2
{
	public int numDistinct(String s, String t)
	{
		final int N = t.length();
		int[] dists = new int[N + 1];
		dists[N] = 1;
		char[] tcs = t.toCharArray();
		for (int i = s.length() - 1; i >= 0; i--) {
			char c = s.charAt(i);
			for (int j = 0; j < N; j++) {
				if (c == tcs[j]) {
					dists[j] += dists[j + 1];
				}
			}
		}
		return dists[0];
	}
	public static void main(String[] args)
	{
		LC115Try2 t = new LC115Try2();
		System.out.println(t.numDistinct("babgbag", "bag"));
	}

}

哈哈哈,希望自己可以回顾。

猜你喜欢

转载自blog.csdn.net/ata_123/article/details/80770599
今日推荐