DP4 最长公共子序列 LCS @geeksforgeeks

macos-lion-dp4-10.8+ios6+xcode4.5.zip macos-lion-dp4-10.8+ios6+xcode4.5.zip 含wifi,ipad,iphone等等全套bt种子 立即下载

LCS Problem Statement: Given two sequences, find the length of longest subsequence present in both of them. A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous. For example, “abc”, “abg”, “bdf”, “aeg”, ‘”acefg”, .. etc are subsequences of “abcdefg”. So a string of length n has 2^n different possible subsequences.

It is a classic computer science problem, the basis of diff (a file comparison program that outputs the differences between two files), and has applications in bioinformatics.

Examples:
LCS for input Sequences “ABCDGH” and “AEDFHR” is “ADH” of length 3.
LCS for input Sequences “AGGTAB” and “GXTXAYB” is “GTAB” of length 4.

The naive solution for this problem is to generate all subsequences of both given sequences and find the longest matching subsequence. This solution is exponential in term of time complexity. Let us see how this problem possesses both important properties of a Dynamic Programming (DP) Problem.

1) Optimal Substructure: 
Let the input sequences be X[0..m-1] and Y[0..n-1] of lengths m and n respectively. And let L(X[0..m-1], Y[0..n-1]) be the length of LCS of the two sequences X and Y. Following is the recursive definition of L(X[0..m-1], Y[0..n-1]).

If last characters of both sequences match (or X[m-1] == Y[n-1]) then
L(X[0..m-1], Y[0..n-1]) = 1 + L(X[0..m-2], Y[0..n-2])

If last characters of both sequences do not match (or X[m-1] != Y[n-1]) then
L(X[0..m-1], Y[0..n-1]) = MAX ( L(X[0..m-2], Y[0..n-1]), L(X[0..m-1], Y[0..n-2])

Examples:
1) Consider the input strings “AGGTAB” and “GXTXAYB”. Last characters match for the strings. So length of LCS can be written as:
L(“AGGTAB”, “GXTXAYB”) = 1 + L(“AGGTA”, “GXTXAY”)

2) Consider the input strings “ABCDGH” and “AEDFHR. Last characters do not match for the strings. So length of LCS can be written as:
L(“ABCDGH”, “AEDFHR”) = MAX ( L(“ABCDG”, “AEDFHR”), L(“ABCDGH”, “AEDFH”) )

So the LCS problem has optimal substructure property as the main problem can be solved using solutions to subproblems.

2) Overlapping Subproblems:
Following is simple recursive implementation of the LCS problem. The implementation simply follows the recursive structure mentioned above.


package DP;

import java.util.Arrays;

// 最长公共子串 Longest Common Subsequence
public class LCS {

	static int dp[][] = null;
	
	public static void main(String[] args) {
		String a = "AGGTAB";
		String b = "GXTXAYB";
		
		dp = new int[a.length()+1][b.length()+1];
		for(int[] row : dp){
			Arrays.fill(row, -1);
		}
		
		System.out.println(lcs2(a.toCharArray(), a.length(), b.toCharArray(), b.length()));
		System.out.println(lcs3(a.toCharArray(), a.length(), b.toCharArray(), b.length()));
//		print();
		System.out.println(lcs(a.toCharArray(), a.length(), b.toCharArray(), b.length()));
		
	}

	/* A Naive recursive implementation of LCS problem */
	// 纯递归O(m*2^n)
	public static int lcs(char[] A, int m, char[] B, int n){
		if(m==0 || n==0){
			return 0;
		}
		
		if(A[m-1] == B[n-1]){
			return 1 + lcs(A, m-1, B, n-1);
		}else{
			return Math.max(lcs(A, m, B, n-1), lcs(A, m-1, B, n));
		}
	}
	
	// DP, top-down O(n^2)
	public static int lcs2(char[] A, int m, char[] B, int n){
		if(m==0 || n==0){
			return 0;
		}
		
		// 如果已经存在dp数组中,直接返回
		if(dp[m][n] != -1){
			return dp[m][n];
		}
		int res = 0;
		if(A[m-1] == B[n-1]){
			res = 1 + lcs2(A, m-1, B, n-1);
		}else{
			res = Math.max(lcs2(A, m, B, n-1), lcs2(A, m-1, B, n));
		}
		dp[m][n] = res;		// 把新值记录到dp数组中
		return res;
	}
	
	// DP, bottom-up O(n^2)
	public static int lcs3(char[] A, int m, char[] B, int n){
		for(int i=0; i<=m; i++){
			for(int j=0; j<=n; j++){
				if(i==0 || j==0){
					dp[i][j] = 0;
				}
				else if(A[i-1] == B[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];
	}
	
	public static void print(){
		for(int i=0; i<dp.length; i++){
			for(int j=0; j<dp[0].length; j++){
				System.out.print(dp[i][j] + " ");
			}
			System.out.println();
		}
	}
}

http://www.geeksforgeeks.org/dynamic-programming-set-4-longest-common-subsequence/

工业互联网工控安全与工业质检AI大模型建设方案.pptx 立即下载

相关推荐

Fortran环境配置:VS2022+Intel oneAPI安装全流程指南

Fortran环境配置:VS2022+Intel oneAPI安装全流程指南

shuyisuisuinian的博客 2万+

dp4-力扣-java-最长递增子序列+ 最长公共子序列

class Solution { public int lengthOfLIS(int[] nums) { if(nums.length<2) return nums.length; int n=nums.length; int res=0; int []dp=new int[n];//dp[i]表示以nums[i]结尾的「上升子序列」的长度 Arrays.fill(dp,1); for(in...

a716121的专栏 417

Android客户端如何设计架构

当我们在新开发一款APP时,我们在初期要如何设计架构呢?在这里我根据我的经验,总结了一些基本的架构思路。 客户端架构设计的时候,首先需要充分考虑到所开发的app的类型,这里我分为功能型和服务型两大类,功能型的app侧重业务和功能,服务型的app侧重服务和运算。下面我就具体来讲讲针对这两种类型的通用架构。 功能型app 功能型app的activity比较多,整个app都以一个个activity承载业务和功能,在设计这类app时,我们需要考虑哪些要素呢? 由于activity比较多,我们需要考虑页面的跳转路由,

子者不语的专栏 1544

DP28 求能变成回文的最小插入字符个数 Minimum insertions to form a palindrome @geeksforgeeks...

Given a string, find the minimum number of characters to be inserted to convert it to palindrome. Before we go further, let us understand with few examples: ab: Number of insertions required i...

系统 运维 195

SAP 资产主数据屏幕增强:对比字段追加与子屏幕/页签 2 种方案优劣

本文深入对比了SAP资产主数据(AS01/AS03)屏幕增强的两种方案:字段追加与子屏幕/页签。从技术实现、业务适配、系统维护等维度分析各自优劣,提供方案选型决策树和混合方案实践建议,帮助企业在SAP实施中做出最优选择。

weixin_28559803的博客 283

INCA基础教程

以软件自带Demo为例记录INCA学习过程,主要内容包括测量与标定。

yunqianrui的博客 6万+

判断是否字符串重组 Scramble String @LeetCode

思路: 1 递归: 简单的说,就是s1和s2是scramble的话,那么必然存在一个在s1上的长度l1,将s1分成s11和s12两段,同样有s21和s22。 那么要么s11和s21是scramble的并且s12和s22是scramble的; 要么s11和s22是scramble的并且s12和s21是scramble的。 如果要能通过OJ,还必须把字符串排序后进行剪枝 http://

1万+

Cursor3.0新界面使用说明

本文摘要:Cursor 3.x版本更新后,提供了两套主界面:Editor(类似VSCode的代码编辑器)和AgentsWindow(以AI智能体为中心的新界面)。Editor适合日常编码,AgentsWindow则支持并行运行多个AI任务、云端协作和多仓库管理。通过Ctrl+E可快速切换布局。文章详细介绍了AI聊天面板的操作技巧、四种工作模式(Agent/Plan/Ask/Debug)的区别,以及AgentsWindow的多任务管理功能。同时提供了Windows快捷键速查、中文化设置方法,并对比了新旧版本的

2501_90421497的博客 724

深入理解递归

大家都知道,递归的本质和栈数据的存取很相似了,都是先进去,但是往往最后处理!再者对于递归函数的局部变量的存储是按照栈的方式去存的,对于每一层的递归函数在栈中都保存了本层函数的局部变量,一边该层递归函数结束时能够保存原来该层的数据!如图:               如上图递归式依次往下进行的,并且在该层递归函数还没结束即将进入下一层递归调用时,将会把该层函数中的局部变量保存起来,以供下次使用!

7758

YOLOv10精度上不去?QAT量化感知训练全流程,INT8推理mAP只掉0.8%

普通PTQ量化虽简单,但无法应对YOLOv10的小目标特征和激活分布波动,导致精度暴跌。QAT通过“模拟量化误差+联合优化权重与量化参数”,让INT8模型精度接近FP16,同时速度提升1.8倍,完美适配实时检测场景(如安防监控、自动驾驶)。该流程已在工业级项目中验证,针对YOLOv10的优化策略(敏感层保护、小目标加权、分阶段训练)可直接迁移至其他YOLO系列(v8/v9),量化后精度损失均可控制在1%以内。

专注于Python爬虫开发,分享爬虫技巧、项目实战与反爬经验,使用Scrapy、BeautifulSoup等工具,解决数据抓取难题。 915

手把手教你学Simulink——基于Simulink的PR(比例谐振)控制器在单相整流中的应用

本文详细介绍了基于Simulink的PR(比例谐振)控制器在单相整流系统中的应用。通过与传统PI控制器的对比,阐述了PR控制器在交流信号跟踪中的优势:可实现50Hz正弦电流的无静差跟踪,THD低于2%,功率因数接近1。文章从PR控制器原理出发,提供了Simulink建模的具体步骤,包括主电路搭建、电压外环设计、PR控制器实现方法(推荐MATLAB Function方式)以及SPWM调制。通过仿真验证了PR控制在稳态和负载突变情况下的优越性能,并探讨了工程实践中的电网频率自适应、多谐振PR等关键技术。该教程为

MHD0815的博客 123

Edit Distance 编辑距离算法 @LeetCode

又是一道典型DP! 我们将人生划为诡异的阶段 我们把这个世界表为丰富的状态 package DP; import java.util.Arrays; /** * Edit Distance * * Given two words word1 and word2, find the minimum number of steps required to conve

5661

华为OD机试新系统真题【迷宫相遇】

华为OD机试 新系统真题【迷宫相遇】,提供C语言、Java、C++、Python、Go、JavaScript源码实现,并提供完整思路讲解,以及在线OJ模拟做题。华为OD机试真题【迷宫相遇】多语言题解。

qq_45776114的博客 764

DP30 求骰子能凑成给定和的组合数 Dice Throw @geeksforgeeks

Given n dice each with m faces, numbered from 1 to m, find the number of ways to get sum X. X is the summation of values on each face when all the dice are thrown. The Naive approach is to find all

4570

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

总结帖:全排列Permutation,子集subset 递归模板

两个经典递归模板,以前写过,现在再过一遍! 基本思路: 如果题目给的输入时数组,首先先要把数组转为ArrayList,因为ArrayList可以很方便地插入,删除,添加! 其次,递归函数的形式都一样,一共有3个参数,分别叫ArrayList done, ArrayList rest, ArrayList> ret 。 done存放已经处理过的数据,rest存放还没处理的数据,ret存

3714

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

DP22 堆盒子问题 Box Stacking Problem @geeksforgeeks

You are given a set of n types of rectangular 3-D boxes, where the i^th box has height h(i), width w(i) and depth d(i) (all real numbers). You want to create a stack of boxes which is as tall as possi

3480

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

DP34 流水线调度问题 Assembly Line Scheduling @geeksforgeeks

A car factory has two assembly lines, each with n stations. A station is denoted by Si,j where i is either 1 or 2 and indicates the assembly line the station is on, and j indicates the number of the s

3373

DP 换硬币问题

设有n种不同面值的硬币,现要用这些面值的硬币来找开待凑钱数m,可以使用的各种面值的硬币个数不限。    找出最少需要的硬币个数,并输出其币值。 package DP; import java.util.Arrays; /** * A country has coins with denominations * 1 = d1 < d2 < · · · < dk

3268

两道递归/回溯好题的分析:printSquares,maxSum

回溯的题目总是有套路的,结合《递归分解的一些方法 和 回溯 笔记》一文,基本上可以套用这个模板来解决回溯题目。 bool solve(configuration conf){ if(no more choices){ // BASE CASE return (conf is goal state); } for(all avail

3105

DP27 2D矩阵中最大的矩形和 Maximum sum rectangle in a 2D matrix @geeksforgeeks

Given a 2D array, find the maximum sum subarray in it. For example, in the following 2D array, the maximum sum subarray is highlighted with blue rectangle and sum of this subarray is 29. This p

3085

最长公共子串 Longest Common Subsequence

动态规划的经典题! package DP; import java.util.Arrays; // 最长公共子串 Longest Common Subsequence public class LCS { static int dp[][] = null; public static void main(String[] args) { String a = "ABCABC

3083

LCS 最长公共子序列

这一片文章写得非常好,放在这里。 LCS:又称 最长公共子序列。 其中子序列(subsequence)的概念不同于串的子串。它是一个不一定连续但按顺序取自字符串X中的字符序列。 例如:串"AAAG"就是串“CGATAATTGAGA”的一个子序列。     字符串的相似性问题可以通过求解两个串间的最长公共子序列(LCS)来得到。 当然如果使用穷举算法列出串的所有子

3074

Recursion 字符串的全排列 String Permutation @CareerCup

字符串全排列的题目,还是套用模板,同样要注意ret的size问题会变化。而且与上一题不同的是不光是要在ret后面添加进新的组合,而且还要移除前面用过的组合。类似一个队列。 另外Java的substring中区间闭合情况是左闭右开 [ ) 所以想把一个字符串拆成两个区间就可以用这一句: for(int j=0; j<=tmp.length(); j++){ // substring

2977

递归函数一定要弄清楚这个函数是做什么用的,基于什么条件返回什么结果!

总结一下:写递归时一定要清楚这个递归函数的每个参数是干嘛用的,以及这个递归函数是干什么用的,返回了什么结果。两篇文章都有提到! So, here are the steps to writing a recursive function. Write a prototype for the recursive function.Write a comment that describes

2879

DP36 如何切出最大长度乘积 Maximum Product Cutting @geeksforgeeks

Given a rope of length n meters, cut the rope in different parts of integer lengths in a way that maximizes product of lengths of all parts. You must make at least one cut. Assume that the length of r

2872
上一篇: DP3 最长上升子序列 LIS @geeksforgeeks
下一篇: DP5 编辑距离 Edit Distance @geeksforgeeks
chiiis
博客等级 码龄14年 422粉丝 429原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值