-1

Given a word composed of opening and closing parentheses and brackets, we can do two operations:

  • Rotate a parentheses or bracket. That is, you can replace ( for ), ) for (, [ for ] and ] for [. This operation has cost 1

  • Replace a parentheses for a bracked and viceversa without changing its orientation. That is, change ( for [, ) for ], [ for ( and ] for ). This operation has cost 2.

Which is the minimum cost to balance the given word properly? For example, given ]( we can achieve [] by rotating twice and replacing once, with a total cost of 4

Ivan
  • 273
  • 2
  • 7

1 Answers1

0

Two possible recursive approaches.

  • The string $(w$ is balanced iff $w$ is of the form $u)v$ where each of $u$ and $v$ are balanced (but either of them may be empty).

  • The (nonempty) string $w$ is balanced iff it is of the form $(u)$ where $u$ is balanced, or it is of the form $uv$ where each of $u$ and $v$ are balanced (and nonempty).

Hendrik Jan
  • 31,459
  • 1
  • 54
  • 109