【区间dp】括号匹配问题总结

问题一

【POJ2955】

Brackets

Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 12165 Accepted: 6448

Description

We give the following inductive definition of a “regular brackets” sequence:

  • the empty sequence is a regular brackets sequence,
  • if s is a regular brackets sequence, then (s) and [s] are regular brackets sequences, and
  • if a and b are regular brackets sequences, then ab is a regular brackets sequence.
  • no other sequence is a regular brackets sequence

For instance, all of the following character sequences are regular brackets sequences:

(), [], (()), ()[], ()[()]

while the following character sequences are not:

(, ], )(, ([)], ([(]

Given a brackets sequence of characters a1a2 … an, your goal is to find the length of the longest regular brackets sequence that is a subsequence of s. That is, you wish to find the largest m such that for indices i1, i2, …, im where 1 ≤ i1 < i2 < … < im ≤ nai1ai2 … aim is a regular brackets sequence.

Given the initial sequence ([([]])], the longest regular brackets subsequence is [([])].

Input

The input test file will contain multiple test cases. Each input test case consists of a single line containing only the characters ()[, and ]; each input test will have length between 1 and 100, inclusive. The end-of-file is marked by a line containing the word “end” and should not be processed.

Output

For each input case, the program should print the length of the longest possible regular brackets subsequence on a single line.

Sample Input

<span style="color:#000000">((()))
()()()
([]])
)[)(
([][][)
end</span>

Sample Output

<span style="color:#000000">6
6
4
0
6</span>

Source

Stanford Local 2004

题目大意,给出一段字符串,然后判断最多有多少个括号是匹配的,比如【】或者()都是可以的

思路:

     与合并石子类似,同样通过小的区间内推导大区间的,有地方需要特判的,比如一段区间的两头;

阶段:枚举区间长度

状态:枚举起点位置,

决策:即从k处断开,判断k为何值时最大(最大括号匹配)

状态转移方程:dp【i】【j】=max(dp【i】【j】,dp【i】【k】+dp【k】【j】);

 还有一个判定:if(s[i]=='('&&s[j]==')'||s[i]=='['&&s[j]==']') 则

                                     dp[i][j]=dp[i+1][j-1]+2;

 代码:

#include<iostream>
#include<cstring>
#include<cstdio>
#include<string>
#define maxn 110
using namespace std;

char s[maxn];
int dp[maxn][maxn];
int main()
{
    while(~scanf("%s",s+1)&&s[1]!='e')
    {
        int n=strlen(s+1);
        memset(dp,0,sizeof(dp));
        for(int len=2;len<=n;len++)
            for(int i=1;i<=n;i++)
        {
            int j=i+len-1;
            if(j>n)
                break;
            if(s[i]=='('&&s[j]==')'||s[i]=='['&&s[j]==']')
            {
                dp[i][j]=dp[i+1][j-1]+2;
            }

            for(int k=i;k<j;k++)
            {
                dp[i][j]=max(dp[i][j],dp[i][k]+dp[k][j]);
            }
        }
        cout<<dp[1][n]<<endl;
    }
}

问题二

【POJ】1141Brackets Sequence

Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 34302 Accepted: 9920 Special Judge

Description

Let us define a regular brackets sequence in the following way: 

1. Empty sequence is a regular sequence. 
2. If S is a regular sequence, then (S) and [S] are both regular sequences. 
3. If A and B are regular sequences, then AB is a regular sequence. 

For example, all of the following sequences of characters are regular brackets sequences: 

(), [], (()), ([]), ()[], ()[()] 

And all of the following character sequences are not: 

(, [, ), )(, ([)], ([(] 

Some sequence of characters '(', ')', '[', and ']' is given. You are to find the shortest possible regular brackets sequence, that contains the given character sequence as a subsequence. Here, a string a1 a2 ... an is called a subsequence of the string b1 b2 ... bm, if there exist such indices 1 = i1 < i2 < ... < in = m, that aj = bij for all 1 = j = n.

Input

The input file contains at most 100 brackets (characters '(', ')', '[' and ']') that are situated on a single line without any other characters among them.

Output

Write to the output file a single line that contains some regular brackets sequence that has the minimal possible length and contains the given sequence as a subsequence.

Sample Input

([(]

Sample Output

()[()]

Source

Northeastern Europe 2001

题目大意:这个的话,就是给出一段括号,然后让你用最少的步数补好他,

思路:

首先,还是区间的问题,从小区间推到大区间,划分问题区间求解,觉得这个题目,输出是个大问题,所以用pos数组来标记某一段区间的情况,如果某一段区间【i , j】上从k处切断有更小补足的解,就用pos【i】【j】=k的形式来保存,如果区间【i,j】的两端是对称的,即不用更改括号,则领pos为-1即可,

阶段:枚举长度

状态:起点的位置

决策:有关pos数组的保存,以及更小值得查找

状态转移方程:

                       1.      if(dp[i][k]+dp[k+1][j]<dp[i][j])
                                             dp[i][j]=dp[i][k]+dp[k+1][j],pos[i][j]=k; 

                       2.      dp[i][j]=dp[i+1][j-1],pos[i][j]=-1;

代码:

    #include<iostream>
    #include<cstring>
    #include<cstdio>
    #include<string>
    #define maxn 110
    #define inf 1<<30
    using namespace std;

    int pos[maxn][maxn],dp[maxn][maxn];
    char s[maxn];

    void show(int l,int r)
    {
        if(l>r)
            return ;
        if(l==r)//最后补足就好
        {
            if(s[l]=='('||s[l]==')')
                printf("()");
            else
                printf("[]");
            return ;
        }
        if(pos[l][r]==-1)//对称区间输出两头,递归中间部分
        {
            putchar(s[l]);
            show(l+1,r-1);
            putchar(s[r]);

        }
        else //断点k处分开即可
        {
            show(l,pos[l][r]);
            show(pos[l][r]+1,r);
        }
    }

    int main()
    {
        while(gets(s+1))
        {
            int n=strlen(s+1);
            memset(dp,0,sizeof(dp));
            for(int i=1; i<=n; i++)
                dp[i][i]=1;
            for(int len=1; len<n; len++)
            {
                for(int i=1; i<=n-len; i++)
                {
                    int j=i+len;
                    dp[i][j]=inf; //找的最小值,记得赋值
                    if(s[i]=='('&&s[j]==')'||s[i]=='['&&s[j]==']')
                        dp[i][j]=dp[i+1][j-1],pos[i][j]=-1;//两端对称情况
                    for(int k=i; k<j; k++)
                        if(dp[i][k]+dp[k+1][j]<dp[i][j])//记录k值
                            dp[i][j]=dp[i][k]+dp[k+1][j],pos[i][j]=k;
                }
            }
            show(1,n);
            cout<<endl;
        }
        return 0;
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 使用动态规划解决最长括号匹配问题的代码如下:int lengthOfLongestValidParentheses(string s) { int n = s.length(), maxLen = 0; vector<int> dp(n, 0); for (int i = 1; i < n; i++) { if (s[i] == ')') { if (s[i - 1] == '(') { dp[i] = (i - 2 >= 0 ? dp[i - 2] : 0) + 2; } else if (i - dp[i - 1] - 1 >= 0 && s[i - dp[i - 1] - 1] == '(') { dp[i] = dp[i - 1] + 2 + ((i - dp[i - 1] - 2 >= 0) ? dp[i - dp[i - 1] - 2] : 0); } maxLen = max(maxLen, dp[i]); } } return maxLen; } ### 回答2: 以下是用动态规划算法求最长括号匹配问题的代码: ```python def longest_valid_parentheses(s: str) -> int: n = len(s) if n == 0: return 0 dp = [0] * n ans = 0 for i in range(1, n): if s[i] == ')': if s[i - 1] == '(': if i >= 2: dp[i] = dp[i - 2] + 2 else: dp[i] = 2 elif i - dp[i - 1] > 0 and s[i - dp[i - 1] - 1] == '(': if i - dp[i - 1] >= 2: dp[i] = dp[i - 1] + dp[i - dp[i - 1] - 2] + 2 else: dp[i] = dp[i - 1] + 2 ans = max(ans, dp[i]) return ans ``` 该算法使用动态规划来求解最长括号匹配问题。定义一个长度为n的dp数组,其中dp[i]表示以下标为i的字符结尾的最长有效括号子串的长度。遍历字符串s,当遇到'('时,不需要做任何计算;当遇到')'时,分为两种情况:如果前一个字符是'(',则dp[i] = dp[i-2] + 2;如果前一个字符是')',则需要判断前一个字符所对应的最长有效括号子串的前一个字符是否是'(',如果是,则dp[i] = dp[i-1] + dp[i-dp[i-1]-2] + 2。最后,取dp数组中的最大值即为最终的结果。算法的时间复杂度为O(n),空间复杂度为O(n)。 ### 回答3: 最长括号匹配问题可以使用动态规划算法来解决,具体代码如下: ```python def longestValidParentheses(s): n = len(s) if n < 2: return 0 dp = [0] * n # dp[i]表示以s[i]为结尾的最长括号长度 max_length = 0 for i in range(1, n): if s[i] == ')': if s[i-1] == '(': # 形如 "()" 的匹配 dp[i] = dp[i-2] + 2 if i >= 2 else 2 elif i - dp[i-1] > 0 and s[i - dp[i-1] - 1] == '(': # 形如 "))" dp[i] = dp[i-1] + dp[i - dp[i-1] - 2] + 2 if i - dp[i-1] >= 2 else dp[i-1] + 2 max_length = max(max_length, dp[i]) return max_length ``` 原理解释: 动态规划的思路是从左到右遍历字符串,维护一个dp数组来记录以当前字符为结尾的最长括号长度。 在遍历过程中,我们需要处理两种情况: 1. 形如 "()" 的匹配:如果当前字符是")",且前一个字符是"(",则可以形成一个有效的括号匹配,这时dp[i]的值可以由dp[i-2] + 2得到,也即前一个最长括号长度再加上当前匹配的长度2。 2. 形如 "))" - 如果当前字符是")",且前一个字符也是")",我们需要判断前一个最长括号匹配的前一个字符是否是"(",如果是,则可以形成一个有效的括号匹配,并且dp[i]的值可以由前一次最长括号长度dp[i-1]再加上到前一个有效括号匹配的前一个位置的最长括号长度dp[i - dp[i-1] - 2],再加上当前匹配的长度2得到。此时需要特别注意边界情况,即当i - dp[i-1] < 2时,没有前一个有效的括号匹配,所以直接加上当前匹配的长度2即可。 遍历结束后,返回dp数组的最大值,即为最长括号匹配的长度。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值