LintCode 581: Longest Repeating Subsequence (DP经典题)

JAVA算法:最长重复子序列(JAVA) JAVA算法:最长重复子序列(JAVA) Longest Repeating Subsequence Given a string, find length of the longest repeating subseequence such that the two subsequence don’t have same string character at same position, i... 阅读详情
  1. Longest Repeating Subsequence

Given a string, find length of the longest repeating subsequence such that the two subsequence don’t have same string character at same position, i.e., any ith character in the two subsequences shouldn’t have the same index in the original string.

Example
Example 1:

Input:“aab”
Output:1
Explanation:
The two subsequence are a(first) and a(second).
Note that b cannot be considered as part of subsequence as it would be at same index in both.
Example 2:

Input:“abc”
Output:0
Explanation:
There is no repeating subsequence

解法1:DP。
注意:
1) 当str[i]==str[j] && i == j时,也要到else分支。
2) 用n+1*n+1矩阵比较方便。

class Solution {
public:
    /**
     * @param str: a string
     * @return: the length of the longest repeating subsequence
     */
    int longestRepeatingSubsequence(string &str) {
        int n = str.size();
        if (n == 0) return 0;
        
        vector<vector<int>> dp(n + 1, vector<int>(n + 1, 0));
        for (int i = 1; i <= n; ++i) {
            for (int j = 1; j <= n; ++j) {
                if (str[i - 1] == str[j - 1] && i != j) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                } else {
                    dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
                }
            }
        }
        
        return dp[n][n];
    }
};

另一种写法是只用n*n的矩阵,稍微繁琐一点。代码如下:

class Solution {
public:
    /**
     * @param str: a string
     * @return: the length of the longest repeating subsequence
     */
    int longestRepeatingSubsequence(string &str) {
        int n = str.size();
        if (n == 0) return 0;
        
        vector<vector<int>> dp(n, vector<int>(n, 0));
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < n; ++j) {
                if (str[i] == str[j] && i != j) {
                    if (i > 0 && j > 0) dp[i][j] = dp[i - 1][j - 1] + 1;
                    else dp[i][j] = 1;
                } else {
                    if (i > 0 && j > 0) dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
                    else if (i == 0 && j > 0) dp[0][j] = dp[0][j - 1];
                    else if (i > 0 && j == 0) dp[i][0] = dp[i - 1][0];
                }
            }
        }
        
        return dp[n - 1][n - 1];
    }
};
CorelDRAW 2019安装指南:从下载到激活的完整步骤 本文提供了一份详细的CorelDRAW 2019安装指南,涵盖从下载安装包、检查系统环境到完成激活的完整步骤。文章重点解析了安装过程中的关键选项设置,并分享了首次启动后的优化配置与常见问题解决方案,旨在帮助用户高效、顺利地完成这款经典矢量设计软件的安装与配置。 阅读详情

相关推荐

Transformer数学推导——Q38 旋转位置编码(RoPE)的复数形式 对注意力分数的几何影响分析

RoPE 的复数形式为自然语言处理中的位置编码提供了创新且有效的解决方案。通过深入的数学理论分析,明确了其对注意力分数的几何影响及在捕捉位置信息方面的优势。在 LLM 的实际应用中,RoPE 复数形式在多个任务和场景中展现出强大的性能,特别是在处理长序列文本时,能够有效捕捉长距离依赖、缓解位置编码局限性并提升处理效率。然而,RoPE 复数形式也面临计算复杂度高、超参数调整困难和位置信息平衡等挑战。通过合理的优化策略和与其他技术的结合,有望进一步提升其性能。

墨顿随笔 1421

Longest Repeating Subsequence

Longest Repeating Subsequence

cxqd1234的博客 350

深入理解DQN中的Q值:核心概念和应用

在强化学习中,Q值(或称为动作价值函数)是核心概念之一。Q值函数 ( Q(s, a) ) 表示在给定状态 ( s ) 下,采取动作 ( a ) 并遵循某策略后,智能体从当前状态到未来状态所能获得的预期总回报。简言之,Q值是评估特定状态和动作对的好坏的指标。

qlkaicx的博客 2979

[LintCode] Longest Repeating Subsequence

Problem Given a string, find length of the longest repeating subsequence such that the two subsequence don’t have same string character at same position, i.e., any ith ch...

weixin_34290631的博客 228

MaaS 商业模式全面分析报告:从技术赋能到商业变现的全链条探索

MaaS(模型即服务)商业模式正成为AI产业主流,2024年上半年中国市场规模达2.5亿元,预计2027年占比将提升至47%。该模式通过云服务提供预训练AI模型,大幅降低企业应用AI的技术门槛和成本。核心盈利方式包括按使用量计费、订阅制、定制化服务等,其中混合模式因灵活性成为趋势。MaaS产业链包含模型提供商、云平台、应用开发商和最终用户,重塑了AI产业格局。随着《数据法案》等监管加强,数据增值服务面临更严格合规要求。未来五年,中国MaaS市场增速预计超50%,用户规模将从2025年2.1亿增至2030年5

芯片行业20年 · 参与定义实现千万级量产出货 · AI芯片PM 2895

MCGS 昆仑通态触摸屏 modbus TCP 数据转发

MCGS触摸屏数据转发modbus TCP数据转发

m0_63451859的博客 2万+

HDU2559-Longest Repeated subsequence(后缀数组)

Longest Repeated subsequence                                                                      Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

wang_128的博客 816

SU-03T1语音模组固件烧录与配置全指南

本文提供SU-03T1离线语音模组固件烧录与配置的完整指南。详细介绍了从硬件连接、软件环境搭建,到在智能公元平台定制唤醒词、命令词及引脚配置,最后使用专用工具完成固件烧录的全流程。重点解析了烧录过程中的关键步骤与常见问题解决方法,帮助开发者快速实现智能语音控制功能。

weixin_29159613的博客 472

HDU 2890 Longest Repeated subsequence

Description Write a program that takes a sequence of number and returns length of the longest repeated  subsequence. A repeated subsequence which repeats identically at least K times without overl

Occult 786

从零到一构建一个智能爬虫 Agent 完整教程

本文将打造一个具备自主决策、动态解析、反反爬、持久化能力的智能爬虫 Agent

数据知道的博客 4799

航空电子系统标准全景图:ARP4754A、ARP4761、DO-178C、DO-254 的协同作用

通过 ARP4754A、ARP4761、DO-178C 和 DO-254 的相互配合,确保航空电子系统的安全性和功能性在开发过程中得到充分保障。每一个文件在不同层面发挥作用,共同构成了一个完整的、系统的开发和验证框架,确保航空电子设备达到适航要求。这些标准不仅帮助开发人员有条理地开发复杂的航空系统,还确保所有系统组件(软件和硬件)在整个生命周期内都能满足最严格的安全和可靠性要求。

qq_41854911的博客 1814

D - Longest Subsequence

思维题

傻的让人心疼 461

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Longest subsequence

String is a very useful thing and a subsequence of the same string is equally important. Now you have a stringsswith lengthnnand a stringttwith lengthmm. Find out the longest subsequenc...

weixin_30612769的博客 203

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

廖雪峰Python教程[完整版]

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

HDU 2890 Longest Repeated subsequence

HDU_2890     在罗穗骞的论文里有说过至少重复K次的可重叠的最长子串该怎么找,只不过这个题改成了不可重叠。我用的是比较暴力的办法,把按height值分组之后每组内sa[i]的值提取出来排个序,然后扫一遍看能不能形成至少K个不重叠的子串。     此外这个题有两个大坑:①题目中所谓的subsequence应该是substring,在HIT的OJ上这个题目的描述就都是用的substrin...

weixin_33924220的博客 172

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

java最长子序列算法,JAVA算法:最长重复子序列(JAVA)

JAVA算法:最长重复子序列(JAVA)Longest Repeating SubsequenceGiven a string, find length of the longest repeating subseequence such that the two subsequence don’t have same string character at same position, i.e....

weixin_39929793的博客 321

Longest Repeated subsequence HDOJ2890

后缀数组,二分长度然后按height分组,每组排序后贪心选择即可 #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include

霁月难逢 彩云易散 1012

Longest Repeated Sequence

描述  You are given a sequence of integers, A = a1, a2, ... an. A consecutive subsequence of A (say ai, ai+1 ... aj) is called a "repeated sequence" if it appears more than once in A (there exists some

SE_and_CS 559

【DP】Longest Repeated Sequence

描述 You are given a sequence of integers, A = a1, a2, ... an. A consecutive subsequence of A (say ai, ai+1 ... aj) is called a "repeated sequence" if it appears more than once in A (there exists

Wu_George的专栏 958

LeetCode刷题记录6-查找字符串的最长串

题目Given a string, find the length of the longest substring without repeating characters.Examples:Given “abcabcbb”, the answer is “abc”, which the length is 3.Given “bbbbb”, the answer is “b”, with the

柠檬柠檬C的博客 506

Given a string, find the length of the longest substring without repeating characters.

Given a string, find the length of the longest substring without repeating characters.Examples:Given "abcabcbb", the answer is "abc", which the length is 3.Given "bbbbb", the answer is "b", with the l...

lifeqiuzhi521的博客 576

LeetCode3 一题学会尺取算法

本文始发于个人公众号:TechFlow 今天和大家聊的问题叫做最长不重复子串,这道题很有意思,我们先来看题面: Given a string, find the length of the longest substring without repeating characters. 翻译 题目只有一句话:给定一个字符串,要求返回不包含重复字符的最长子串的长度。 样例 Example...

TechFlow的博客 429

LeetCode : Given a string, find the length of the longest serial substring without repeating charact...

Given a string, find the length of thelongest serialsubstringwithout repeating characters. Examples: Given"abcabcbb", the answer is"abc", which the length is 3. Given"bbbbb", the answer is"b...

weixin_34024034的博客 347

【HDU2890 Longest Repeated subsequence】 后缀数组之重复k次最长子序列(不可覆盖)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2890 题目大意:给你一个含n个数的序列,再给你一个k,让你求最少重复k次的最长子序列(子序列不能重叠)。 解题思路:先吐槽一下,题意不明,蛋疼许久。 我可以这么理解 : 1、保证子序列重复次数cnt大于k的前提下,len为一个子序列长度,然后最长子序列最长,即cnt*le...

baidui8622的博客 459
上一篇: LintCode 631: Maximal Square II (DP经典题)
下一篇: LintCode 393: Best Time to Buy and Sell Stock IV (买股票 DP经典题)
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值