This problem can solved elegantly using dynamic programming.
We Maintain the arrays:
- CNT[I][J] ---Number of parentheses needed to add within s[i. J] inclusively;
- Pos[i][j] ---Position to add the parenthesis within s[i. J] inclusively.
Then there is three cases:
- Cnt[i][i] = 1;
- If s[i] = = S[j], cnt[i][j] = cnt[i + 1][j-1], pos[i][j] = 1 (no need to add any parenthesis) ;
- If s[i]! = S[j], cnt[i][j] = Min_{k = i, i + 1, ..., j}cnt[i][k] + cnt[k + 1][j], pos[i][j] = k (Choose the best position to add the parenthesis).
After computing CNT and POS, we'll print the resulting parentheses recursively.
My accepted code is as follows. In fact, I spent a lot timg on debugging the wrong Answer error due to incorrect input/output. You may try the problem at this link.
1#include <iostream>2#include <cstdio>3#include <vector>4#include <cstring>5 6 using namespacestd;7 8 #defineInt_max 0x7fffffff9 #defineVEC1D vector<int>Ten #defineVec2d vector<vec1d > One A voidPrintChar* S, vec2d& POS,intHeadinttail) { - if(Head > Tail)return; - if(Head = =tail) { the if(S[head] = ='('|| S[head] = =')') -printf"()"); - Elseprintf"[]"); - } + Else if(Pos[head][tail] = =-1) { -printf"%c", S[head]); +Print (S, POS, head +1, tail-1); Aprintf"%c", S[tail]); at } - Else { - print (S, POS, Head, Pos[head][tail]); -Print (S, POS, Pos[head][tail] +1, tail); - } - } in - voidSolveChar* S, vec2d& cnt, vec2d&POS) { to intn =strlen (s); + for(inti =0; I < n; i++) -Cnt[i][i] =1; the for(intL =1; l < N; l++) { * for(inti =0; i < n-l; i++) { $ intj = i +l;Panax NotoginsengCNT[I][J] =Int_max; - if((s[i] = ='('&& S[j] = =')') || (S[i] = ='['&& S[j] = =']')) { theCNT[I][J] = cnt[i +1][j-1]; +POS[I][J] =-1; A } the for(intK = i; K < J; k++) { + if(Cnt[i][k] + cnt[k +1][J] <Cnt[i][j]) { -CNT[I][J] = Cnt[i][k] + cnt[k +1][j]; $POS[I][J] =K; $ } - } - } the } -Print (S, POS,0N1);Wuyiprintf"\ n"); the } - Wu intMainvoid) { - Chars[ the]; About while(gets (s)) { $ intn =strlen (s); -Vec2d CNT (n, vec1d (n,0)); - vec2d POS (n, vec1d (n)); - solve (S, CNT, POS); A } + return 0; the}
[POJ Solutions] Brackets Sequence