Title Description
Description
We define a valid parenthesis sequence using the following rules:
(1) The empty sequence is legal
(2) If s is a valid sequence, then (s) and [s] are both legal
(3) If both A and B are legal, then AB and BA are also legal
For example, the following is a valid parenthesis sequence:
(), [], (()), ([]), ()[], ()[()]
The following is an illegal bracket sequence:
(, [, ], )(, ([]) , ([()
Now given some sequences consisting of ' (', ') ', ' [', ', '] ', add as few parentheses as possible to get a valid parenthesis sequence.
Enter a description input
Description
Enter the include number sequence S. Contains up to 100 characters (four characters: ' (', ') ', ' [' and '] '), all on one line, with no other extra characters in the middle.
outputs description output
Description
The minimum number of parentheses is required to make the parentheses sequence s a valid sequence.
sample input to
sample
([()
Sample output Sample
outputs
2
The last possible situation before turning an illegal s into a legitimate one:
1) S shape (s′) or [s′]:
Just change the s′ to be legal.
f[i,j]= F[i+1,j-1]
2) S shape such as (s′ or [s′:
First turn s′ into legal, right plus) or].
f[i,j]= f[i+1,j]+1
3) S shaped like s′) or s′]:
First the s′ into a legal, the left add (or [can.
f[i,j]= f[i,j-1]+1
4) The length of the sequence greater than 1 sisi+1 .... The SJ-1SJ is divided into two parts:
Si ... Sk,sk+1 ..... Sj
into a sequence of rules.
Then: F[i,j]=f[i,k]+f[k+1,j];i<=k<=j-1;
The above 4 cases take the minimum value.
The code is as follows:
The father is afraid of the epigenetic, the husband is not light young.
Copyright NOTICE: Reprint Please specify source [ametake Copyright]http://blog.csdn.net/ametake Welcome to see
"Basic Exercise" "Interval DP" codevs3657 parentheses sequence