每日一题动态规划-3 【LeetCode 1143.最长公共子序列】

题目链接:LeetCode 1143.最长公共子序列

下面提供了两种思路

  • 第一种是递归的思想,提交到平台上会超时
  • 第二种是经典dp思想,不会超时,第二种解法是从第一种递归解法的基础上得到的

递归代码:

package com.dp;

//链接:https://leetcode.com/problems/longest-common-subsequence/
public class Code5_LongestCommonSubsequence {
	public int longestCommonSubsequence1(String text1, String text2) {
		return process1(text1.toCharArray(), text2.toCharArray(), text1.length() - 1, text2.length() - 1);
	}

	public int process1(char[] str1, char[] str2, int i, int j) {
		if (i == 0 && j == 0) {
			return str1[i] == str2[j] ? 1 : 0;
		} else if (i == 0) {
			if (str1[i] == str2[j]) {
				return 1;
			} else {
				return process1(str1, str2, i, j - 1);
			}
		} else if (j == 0) {
			if (str1[i] == str2[j]) {
				return 1;
			} else {
				return process1(str1, str2, i - 1, j);
			}
		} else {
			int p1 = process1(str1, str2, i - 1, j);// 最长公共子序列有可能以j结尾,但是必定不以i结尾
			int p2 = process1(str1, str2, i, j - 1);// 最长公共子序列有可能以i结尾,但是必定不以j结尾
			int p3 = str1[i] == str2[j] ? 0 : 1 + process1(str1, str2, i - 1, j - 1);// 最长公共子序列不以i结尾也不以j结尾
			return Math.max(p1, Math.max(p2, p3));
		}
	}
}

经典dp代码:

package com.dp;

//链接:https://leetcode.com/problems/longest-common-subsequence/
public class Code5_LongestCommonSubsequence {
public int longestCommonSubsequence2(String text1, String text2) {
		char[] str1 = text1.toCharArray();
		char[] str2 = text2.toCharArray();
        int N = str1.length;
        int M = str2.length;
		int[][] dp = new int[N][M];
		dp[0][0] = str1[0] == str2[0] ? 1 : 0;
		for (int j = 1; j < M; j++) {
			dp[0][j] = str1[0] == str2[j] ? 1 : dp[0][j - 1];
		}
		for (int i = 1; i < N; i++) {
			dp[i][0] = str1[i] == str2[0] ? 1 : dp[i - 1][0];
		}

		for (int i = 1; i < N; i++) {
			for (int j = 1; j < M; j++) {
				int p1 = dp[i - 1][j];// 最长公共子序列有可能以j结尾,但是必定不以i结尾
				int p2 = dp[i][j - 1];// 最长公共子序列有可能以i结尾,但是必定不以j结尾
				int p3 = str1[i] == str2[j] ? 1 + dp[i - 1][j - 1] : 0;// 最长公共子序列不以i结尾也不以j结尾
				dp[i][j] = Math.max(p1, Math.max(p2, p3));
			}
		}
		return dp[N - 1][M - 1];
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值