题意:
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 ≤ n, ai1ai2 … 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
((()))
()()()
([]])
)[)(
([][][)
end
Sample Output
6
6
4
0
6
思路:
题意:找出给定字符串中最大能够匹配上的括号数量;
dp[i][j]表示[i,j]这段区间里面的最长子序列的长度,当s[i] =s[j] 是,可以转换为子问题:求[i+1,j-1]的最长合法子序列的长度,但是不能就直接求得,如 [][] , 可知答案应为4,但如果直接求得话就是2。
所以不管s[i] 和s[j] 是否相等,都要枚举中间得元素。
区间dp写成记忆化得时候一定要处理好边界情况。
状态表示:
1):如果序列式形如(s‘)或[s’],则只需将s’变为规则的即可。dp[l][r]=min(dp[[l][r],dp[l+1][r-1])
2):如果序列形如(s’,[s’,s’),s’],则删掉边上的不规则的,将s’变为规则的即可。dp[l][r]=min(dp[l][r],dp[l+1][r]+1,dp[l][r-1]+1)
3):对任意大于1的序列,均可划分为两部分,dp[l][r]=min(dp[l][r],dp[l][k]+dp[k+1][r])
代码:
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
const int maxn=105;
int dp[maxn][maxn];
int n;
bool match(char &a,char &b)
{//配对
if((a=='('&&b==')' )||(a=='['&&b==']'))
return true;
return false;
}
int main()
{
string s;
while(cin>>s)
{
if(s=="end") return 0;
memset(dp,0,sizeof(dp));
n=s.length();
for(int i=0;i<=n;i++)
{
dp[i][i]=1;
}
for(int i=n-2;i>=0;i--)
{
for(int j=i+1;j<n;j++)
{
dp[i][j]=n;
if(match(s[i],s[j]))
dp[i][j]=min(dp[i][j],dp[i+1][j-1]);
for(int k=i;k<j;k++)
{
dp[i][j]=min(dp[i][j],dp[i][k]+dp[k+1][j]);
}
}
}
printf("%d\n",n-dp[0][n-1]);
}
return 0;
}