Week Training: 516 Longest Palindromic Subsequence

本文介绍了一种使用动态规划求解最长回文子序列问题的方法。通过二维数组记录子问题解,递归地更新状态,当序列两端字符相同时增加长度,否则选择较长子序列。初始状态为每个单独字符都是长度为1的回文子序列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The main difficulty is we have to find the length of longest palindromic subsequence, but not a substring. Which means the sequence may not be continuous. There are many ways to do, but using dynamic programming, the method is concise but hard to come up with. We first use a 2d array length[i][j] to store the length of each subsequence, with i, j means the length of longest PS between i and j in the string. The recurrence part add the length by 2 when the number left and right of the current sequence is the same and when not, the bigger one is chosen. The initial state is length[i][i]=1.

class Solution {
public:
    int longestPalindromeSubseq(string s) {
        int l = s.length();
        int length[1000][1000];
        for(int i=l-1;i>=0;i--){
            length[i][i]=1;
            for(int j=i+1;j<l;j++){
                if(s[i]==s[j])
                    length[i][j]=length[i+1][j-1]+2;
                else
                    length[i][j]=max(length[i+1][j],length[i][j-1]);
            }
        }
        return length[0][l-1];
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值