Open azl397985856 opened 1 year ago
··· class Solution: def longestCommonSubsequence(self, s: str, t: str) -> int:
# 状态表示: f[i][j] 表示 s的前i个字符和t的前j个字符的公共子序列所有方案
# 属性: max
# 集合划分, 如果 s[i]和t[j] 相同的话
# f[i][j] = f[i-1][j-1] + 1
# 如果不同, 就是两者取max
m, n = len(s), len(t)
f = [[0] * (n+1) for _ in range(m+1)]
for i in range(1, m+1):
for j in range(1, n+1):
if s[i-1] == t[j-1]:
f[i][j] = f[i-1][j-1] + 1
else:
f[i][j] = max(f[i-1][j], f[i][j-1])
return f[-1][-1]
···
class Solution { public int longestCommonSubsequence(String text1, String text2) { int m = text1.length(), n = text2.length(); int[][] dp = new int[m + 1][n + 1]; //初始化dp[0][] 和dp[][0]为0,因为当一个字符串长度为0时,那么他们的LCS长度也为0 Arrays.fill(dp[0], 0); for(int i = 0; i <= m; i++){ dp[i][0] = 0; }
for(int i = 1; i <= m; i++){
for(int j = 1; j <= n; j++){
if(text1.charAt(i - 1) == text2.charAt(j - 1))//该字符可以加入LCS
dp[i][j] = 1 + dp[i - 1][j - 1];
else{//该位置的字符不相等,至少有一个不能加入LCS,先选择当前局部最优解,即选择前面的较大值
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[m][n];
}
}
··· class Solution: def maxCandies(self, status: List[int], candies: List[int], keys: List[List[int]], containedBoxes: List[List[int]], initialBoxes: List[int]) -> int: n = len(status) q = deque() owned_keys = set() owned_boxes = set() for x in initialBoxes: if status[x]: q.append(x) else: owned_boxes.add(x) ans = 0 while q: t = q.popleft() ans += candies[t]
# 如果不能, 将key先存下
for x in keys[t]:
if x in owned_boxes:
q.append(x)
owned_boxes.remove(x)
else:
owned_keys.add(x)
for x in containedBoxes[t]:
if status[x]:
q.append(x)
elif x in owned_keys:
q.append(x)
owned_keys.remove(x)
else:
owned_boxes.add(x)
return ans
···
class Solution {
public int longestCommonSubsequence(String text1, String text2) {
int m = text1.length(), n = text2.length();
int[][] f = new int[m+1][n+1];
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (text1.charAt(i-1) == text2.charAt(j-1)) {
f[i][j] = f[i-1][j-1] + 1;
} else {
f[i][j] = Math.max(f[i-1][j], f[i][j-1]);
}
}
}
return f[m][n];
}
}
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: m, n = len(text1), len(text2) dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if text1[i - 1] == text2[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
return dp[m][n]
dp[i][j] 表示⻓度为i的t1子串和⻓度是j的t2子串的最⻓公共子序列⻓度 。递推公式:如果两个字母相等,则是上一个dp[i-1][j-1]+1,如果不相等,则取三种可能性最大的。
/**
* @param {string} text1
* @param {string} text2
* @return {number}
*/
var longestCommonSubsequence = function(text1, text2) {
const n = text1.length
const m = text2.length
// dp[i][j]表示⻓度为i的t1子串和⻓度是j的t2子串的最⻓公共子序列⻓度
const dp = new Array(n+1).fill().map(() => new Array(m+1).fill(0));
for (let i = 1;i<=n; i++) {
for (let j = 1;j<=m;j++) {
if (text1[i-1] === text2[j-1]) {
dp[i][j] = dp[i-1][j-1] + 1;
} else {
// 3种可能
dp[i][j] = Math.max(dp[i-1][j] , dp[i][j-1], dp[i-1][j-1]);
}
}
}
return dp[n][m];
};
时间:O(nm) 空间:O(nm)
动态规划
C++ Code:
class Solution {
public:
int longestCommonSubsequence(string text1, string text2) {
int m = text1.length(), n = text2.length();
vector<vector<int>> dp(m + 1, vector<int>(n + 1));
for (int i = 1; i <= m; i++) {
char c1 = text1.at(i - 1);
for (int j = 1; j <= n; j++) {
char c2 = text2.at(j - 1);
if (c1 == c2) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[m][n];
}
};
复杂度分析
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int:
dp = [[0 for _ in range(len(text1)+1)] for _ in range(len(text2)+1)]
ans= 0
for i in range(1,len(text2)+1):
for j in range(1,len(text1)+1):
if text2[i-1] == text1[j-1]:
dp[i][j] = dp[i-1][j-1] + 1
ans = max(ans,dp[i][j])
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
return ans
code
public int longestCommonSubsequence(String text1, String text2) {
int m = text1.length();
int n = text2.length();
int[] dp = new int[n + 1];
for (int j = 1; j <= m; j++) {
int prev = dp[0];
for (int i = 1; i <= n; i++) {
int tmp = dp[i];
if (text1.charAt(j - 1) == text2.charAt(i - 1))
dp[i] = prev + 1;
else
dp[i] = Math.max(dp[i], dp[i - 1]);
prev = tmp;
}
}
return dp[n];
}
class Solution {
public int longestCommonSubsequence(String t1, String t2) {
char[] c1 = t1.toCharArray();
char[] c2 = t2.toCharArray();
int[][] dp = new int[c1.length + 1][c2.length + 1];
for(int i = 1; i <= c1.length; ++i){
for(int j = 1; j <= c2.length; ++j){
if(c1[i - 1] == c2[j - 1]){
dp[i][j] = dp[i - 1][j - 1] + 1;
}else{
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[c1.length][c2.length];
}
}
class Solution:
def longestCommonSubsequence(self, s1, s2):
dp = [[0 for i in range(len(s1)+1)] for j in range(len(s2)+1)]
for i in range(1,len(dp)):
for j in range(1,len(dp[i])):
s1_sub = s1[:j]
s2_sub = s2[:i]
if s1_sub[-1] == s2_sub[-1]:
dp[i][j] = dp[i-1][j-1] + 1
else:
dp[i][j] = max(dp[i][j-1],dp[i-1][j])
return dp[-1][-1]
DP
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
m, n = len(text1), len(text2)
dp, dpPrev = [0] * (n+1), [0] * (n+1)
for i in range(1, m+1):
for j in range(1, n+1):
if text1[i-1] == text2[j-1]:
dp[j] = dpPrev[j-1] + 1
else:
dp[j] = max(dp[j-1], dpPrev[j])
dp, dpPrev = dpPrev, dp
return dpPrev[n]
...
class Solution:
def longestCommonSubsequence(self, A: str, B: str) -> int:
m,n = len(A), len(B)
ans = 0
dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if A[i-1] == B[j-1]:
dp[i][j] = dp[i - 1][j - 1] + 1
ans = max(ans, dp[i][j])
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
return ans
/**
subsequence: 没有对字母顺序的要求
TC: O(NM) SC: O(NM)
*/
// SC 优化 成 O(M): 滚动数组
class Solution {
public int longestCommonSubsequence(String s1, String s2) {
int N = s1.length(), M = s2.length();
int[][] dp = new int[2][M + 1];
for (int i = 1; i <= N; i++) {
int a = i & 1, b = (i - 1) & 1;
char c1 = s1.charAt(i - 1);
for (int j = 1; j <= M; j++) {
if (c1 == s2.charAt(j - 1))
dp[a][j] = 1 + dp[b][j - 1];
else
dp[a][j] = Math.max(dp[a][j - 1], dp[b][j]);
}
}
return dp[N & 1][M];
}
}
class Solution1 {
public int longestCommonSubsequence(String s1, String s2) {
int N = s1.length(), M = s2.length();
// dp[N][M] = len of longest subseq from s1[0... N - 1] s2[0... M - 1]
int[][] dp = new int[N + 1][M + 1];
// Base case: dp[0][0] = 0;
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= M; j++) {
if (s1.charAt(i - 1) == s2.charAt(j - 1))
dp[i][j] = 1 + dp[i - 1][j - 1];
else
dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]);
}
}
return dp[N][M];
}
}
动态规划。定义二维数组dp,dp[i][j]
表示从头开始的长度为i的text1的子字符串和从头开始长度为j的text2的子字符串的LCS的长度。状态转移方程:分为两种情况,如果对应index上的字符相同,那么dp[i][j] = dp[i - 1][j - 1] + 1
,如果对应index上的字符不同,那么dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
。用双层循环最后求得dp[text1.length()][text2.length()]
即为最终结果。
class Solution {
public int longestCommonSubsequence(String text1, String text2) {
int len1 = text1.length();
int len2 = text2.length();
int[][] dp = new int[len1 + 1][len2 + 1];
// dp[i][j] corresponds to the length of LCS between the substring of text1 starting at index 0 with length i and the substring of text2 starting at index 0 with length j
char[] arr1 = text1.toCharArray();
char[] arr2 = text2.toCharArray();
for (int i = 1; i <= len1; i++) {
for (int j = 1; j <= len2; j++) {
// if characters in text1 and text 2 are the same
if (arr1[i - 1] == arr2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
}
// if characters are different
else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[len1][len2];
}
}
复杂度分析
class Solution {
public:
int longestCommonSubsequence(string text1, string text2) {
int n1=text1.size(),n2=text2.size();
vector<vector<int>> dp(n1+1,vector<int>(n2+1));
for(int i=0;i<n1;i++){
for(int j=0;j<n2;j++){
if(text1[i]==text2[j]){
dp[i+1][j+1]=dp[i][j]+1;
}else{
dp[i+1][j+1]=max(dp[i][j+1],dp[i+1][j]);
}
}
}
return dp[n1][n2];
}
};
class Solution {
public:
int longestCommonSubsequence(string text1, string text2) {
int m = text1.length(), n = text2.length();
vector<vector<int>> dp(m + 1, vector<int>(n + 1));
for (int i = 1; i <= m; i++) {
char c1 = text1.at(i - 1);
for (int j = 1; j <= n; j++) {
char c2 = text2.at(j - 1);
if (c1 == c2) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[m][n];
}
};
class Solution {
public int longestCommonSubsequence(String text1, String text2) {
int m = text1.length();
int n = text2.length();
int[][] dp = new int[m + 1][n + 1];
int res = 0;
for(int i = 1; i <= m; i++){
for(int j = 1; j <= n; j++){
dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]);
if(text1.charAt(i - 1) == text2.charAt(j - 1)){
dp[i][j] = Math.max(dp[i][j], dp[i - 1][j - 1] + 1);
}
}
}
return dp[m][n];
}
}
dp[i][j]指的是字符串text1截止到i和字符串text2截止到j的最长公共子序列的长度 递推:当text1[i - 1] === text2[j - 1]时有 -> dp[i][j] = dp[i - 1][j - 1] + 1,当text1[i - 1] !== text2[j - 1]时有 -> dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1])
const longestCommonSubsequence = (text1, text2) => {
const len1 = text1.length, len2 = text2.length
// 取len1+1,len2+1的原因是要甩出i - 1, j - 1的量
const dp = new Array(len1 + 1).fill(0).map(() => new Array(len2 + 1).fill(0))
for (let i = 1; i <= len1; i++) {
for (let j = 1; j <= len2; j++) {
if (text1[i] == text2[j]) {
dp[i][j] = dp[i - 1][j - 1] + 1
} else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1])
}
console.log('i ->', i, 'j ->', j, 'dp->', dp[i][j])
}
}
return dp[len1][len2]
}
复杂度分析: 时间复杂度:O(N^2) 空间复杂度:O(N)
class Solution {
public int longestCommonSubsequence(String text1, String text2) {
int m = text1.length(), n = text2.length();
int[][] f = new int[m+1][n+1];
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (text1.charAt(i-1) == text2.charAt(j-1)) {
f[i][j] = f[i-1][j-1] + 1;
} else {
f[i][j] = Math.max(f[i-1][j], f[i][j-1]);
}
}
}
return f[m][n];
}
}
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: n1=len(text1)+1 n2=len(text2)+1 dp=[[0 for in range(n2)] for in range(n1)]
for i in range(1,n1):
for j in range(1,n2):
if text1[i-1]==text2[j-1]:
dp[i][j]=dp[i-1][j-1]+1
else:
dp[i][j]=max(dp[i-1][j],dp[i][j-1])
return dp[-1][-1]
class Solution { public int longestCommonSubsequence(String t1, String t2) { char[] c1 = t1.toCharArray(); char[] c2 = t2.toCharArray(); int[][] dp = new int[c1.length + 1][c2.length + 1]; for(int i = 1; i <= c1.length; ++i){ for(int j = 1; j <= c2.length; ++j){
if(c1[i - 1] == c2[j - 1]){
dp[i][j] = dp[i - 1][j - 1] + 1;
}else{
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[c1.length][c2.length];
}
}
class Solution {
public int longestCommonSubsequence(String text1, String text2) {
int m = text1.length();
int n = text2.length();
//初始化
int[][] dp = new int[m + 1][n + 1];
//遍历顺序
for(int i = 1; i <= m;i++){
for(int j = 1;j <= n;j++){
if(text1.charAt(i - 1) == text2.charAt(j - 1)){
dp[i][j] = dp[i - 1][j - 1] + 1;
}else{
dp[i][j] = Math.max(dp[i - 1][j],dp[i][j - 1]);
}
}
}
return dp[m][n];
}
}
class Solution {
public:
int longestCommonSubsequence(string text1, string text2) {
int m = text1.length(), n = text2.length();
vector<vector<int>> dp(m + 1, vector<int>(n + 1));
for (int i = 1; i <= m; i++) {
char c1 = text1.at(i - 1);
for (int j = 1; j <= n; j++) {
char c2 = text2.at(j - 1);
if (c1 == c2) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[m][n];
}
};
动态规划
class Solution {
public:
int longestCommonSubsequence(string text1, string text2) {
int m = text1.size(), n = text2.size();
vector<vector<int>> dp(m + 1, vector(n + 1, 0));
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (text1[i - 1] == text2[j - 1])
dp[i][j] = dp[i - 1][j - 1] + 1;
else
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
}
}
return dp[m][n];
}
};
复杂度分析
Java Code:
class Solution {
public int longestCommonSubsequence(String text1, String text2) {
char[] t1 = text1.toCharArray();
char[] t2 = text2.toCharArray();
int length1 = t1.length;
int length2 = t2.length;
int[][] dp = new int[length1+1][length2+1];
for (int i = 1; i < length1 +1; i++) {
for (int j = 1; j < length2 +1; j++) {
if (t1[i-1] == t2[j-1]){
// 找到一个 lcs 的元素,继续往前找
dp[i][j] = 1+ dp[i-1][j-1];
}else {
dp[i][j] = Math.max(dp[i-1][j],dp[i][j-1]);
}
}
}
return dp[length1][length2];
}
}
dp建模套路
class Solution:
def longestCommonSubsequence(self, A: str, B: str) -> int:
m, n = len(A), len(B)
ans = 0
dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if A[i - 1] == B[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
ans = max(ans, dp[i][j])
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
return ans
class Solution {
public int longestCommonSubsequence(String text1, String text2) {
int n = text1.length();
int m = text2.length();
char[] charArray1 = text1.toCharArray();
char[] charArray2 = text2.toCharArray();
int[][] dp = new int[n + 1][m + 1];
int ans = 0;
for (int i = 1; i < n + 1; i++) {
for (int j = 1; j < m + 1; j++) {
if (charArray1[i-1] == charArray2[j-1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
ans = Math.max(ans, dp[i][j]);
} else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return ans;
}
}
class Solution:
def longestCommonSubsequence(self, s: str, t: str) -> int:
m, n = len(s), len(t)
f = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m+1):
for j in range(1, n+1):
if s[i-1] == t[j-1]:
f[i][j] = f[i-1][j-1] + 1
else:
f[i][j] = max(f[i-1][j], f[i][j-1])
return f[-1][-1]
在 text1 取长度为 i 的字符串,在 text2 取长度为 j 的字符串,并记录下他们的子串长度。每次改变一个字符,可以通过前面记录过的子串长度来推导。
class Solution {
public:
int longestCommonSubsequence(string text1, string text2) {
int len1 = text1.length(), len2 = text2.length();
vector<vector<int>> lens(len1 + 1, vector<int>(len2 + 1));
for (int i = 1; i <= len1; i++) {
for (int j = 1; j <= len2; j++) {
if (text1[i - 1] == text2[j - 1]) {
lens[i][j] = lens[i - 1][j - 1] + 1;
} else {
lens[i][j] = max(lens[i - 1][j], lens[i][j - 1]);
}
}
}
return lens[len1][len2];
}
};
1143.最长公共子序列
入选理由
暂无
题目地址
https://leetcode-cn.com/problems/longest-common-subsequence
前置知识
题目描述
给定两个字符串 text1 和 text2,返回这两个字符串的最长公共子序列的长度。
一个字符串的 子序列 是指这样一个新的字符串:它是由原字符串在不改变字符的相对顺序的情况下删除某些字符(也可以不删除任何字符)后组成的新字符串。 例如,"ace" 是 "abcde" 的子序列,但 "aec" 不是 "abcde" 的子序列。两个字符串的「公共子序列」是这两个字符串所共同拥有的子序列。
若这两个字符串没有公共子序列,则返回 0。
示例 1:
输入:text1 = "abcde", text2 = "ace" 输出:3
解释:最长公共子序列是 "ace",它的长度为 3。 示例 2:
输入:text1 = "abc", text2 = "abc" 输出:3 解释:最长公共子序列是 "abc",它的长度为 3。 示例 3:
输入:text1 = "abc", text2 = "def" 输出:0 解释:两个字符串没有公共子序列,返回 0。
提示:
1 <= text1.length <= 1000 1 <= text2.length <= 1000 输入的字符串只含有小写英文字符。