Grouping Symbols Maximum Length Balanced Subsequence

安稳与你 提交于 2019-12-12 08:15:26

问题


Consider B to be a sequence of grouping symbols (, ), [, ], {, and }. B is called a Balanced sequence if it is of length 0 or B is of one of the following forms: { X } Y or [ X ] Y or { X } Y where X and Y are Balanced themselves. Example for Balanced : ( ) - { [ ] ( ) } [ ] - ...

Now the question is to find an efficient algorithm to find maximum length balanced subsequence (not necessarily contiguous) of a given input which is an string of these grouping symbols.

For example if input is ( ) { ( [ ) ] { ( ] ) } } [ ] , one of the max-length subsequences is ( ) { [ ] { ( ) } } [ ]

I am almost sure the solution is DP but anyway I solve it I find examples in which my algorithm doesn't work. there is only one approach I am sure about, which is a combination of DP and Divide and Conquer. But it is not efficient because anyway D&C part is going to solve some overlapping problems over and over again.


回答1:


Let's make a couple of simple observation:

  1. Any balanced subsequence can be represented as A1 X A2 Y, where A1 and A2 are two matched brackets((), [] or {}), X and Y are balanced subsequences(they can be empty). It is true because there is a leftmost bracket in any balanced non-empty subsequence and it must be matched to something.

  2. X and Y are independent. If it is not the case, the subsequence is not balanced.

These observations give us a dynamic programming solution:

Let's assume f(L, R) is the longest balanced subsequence for [L, R] subarray. The base is an empty subarray. Transition are as follows:

f(L, R) = max(   
     f(L + 1, R) // ignore the first element    
     max(f(L + 1, K - 1) + 2 + f(K + 1, R)) for all K if brackets at positions L and K match
)

The time complexity is O(N^3) because there are O(N^2) subarrays and there are O(N) transitions for each of them. It is possible to reconstruct the longest subsequence itself using standard answer reconstruction techniques.



来源:https://stackoverflow.com/questions/27583771/grouping-symbols-maximum-length-balanced-subsequence

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!