leetcode_115_不同的子序列@@dp

在这里插入图片描述
在这里插入图片描述

首先就是暴力尝试但是会超时,通过54/63测试用例

	public static int numDistinct1(String s, String t) {
		char[] sChars = s.toCharArray();
		char[] tChars = t.toCharArray();
		int sLen = sChars.length;
		int tLen = tChars.length;
		if (tLen == 1) {
			int count = 0;
			for (int i = 0; i < sLen; i++) {
				if (sChars[i] == tChars[0]) {
					count++;
				}
			}
			return count;
		}
		int count = 0;
		for (int i = 0; i < sLen; i++) {
			if (sChars[i] == tChars[0]) {
				count += numDistinct1(s.substring(i + 1), t.substring(1));
			}
		}
		return count;
	}

再就是尝试动态规划,找这个状态转移方程花了一个多小时

public int numDistinct(String s, String t) {
		char[] sChars = s.toCharArray();
		char[] tChars = t.toCharArray();
		int sLen = sChars.length;
		int tLen = tChars.length;
		int[][] dp = new int[sLen + 1][tLen + 1];
		int count = 0;
		for (int i = 1; i <= sLen; i++) {
			if (sChars[i - 1] == tChars[0]) {
				count++;
				dp[i][1] = count;
			} else {
				dp[i][1] = dp[i - 1][1];
			}
		}
		for (int i = 1; i <= sLen; i++) {
			for (int j = 2; j <= tLen; j++) {
				if (sChars[i - 1] == tChars[j - 1]) {
					dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j];
	               //dp[i][j]表示前i个元素中包含多少个前j个元素
				} else {
					dp[i][j] = dp[i - 1][j];
				}
			}
		}
		return dp[sLen][tLen];
	}

猜你喜欢

转载自blog.csdn.net/ruochen82155551/article/details/107545953