实现一个算法打印出n对括号的有效组合

转载于:http://www.code123.cc/841.html 

侵删

题目

实现一个算法打印出n对括号的有效组合。

例如:

输入:3 (3对括号)

输出:((())), (()()), (())(), ()(()), ()()()

解答

对于括号的组合,要考虑其有效性。比如说,)(, 它虽然也是由一个左括号和一个右括号组成,但它就不是一个有效的括号组合。 那么,怎样的组合是有效的呢?对于一个左括号,在它右边一定要有一个右括号与之配对, 这样的才能是有效的。所以,对于一个输出,比如说(()()), 从左边起,取到任意的某个位置得到的串,左括号数量一定是大于或等于右括号的数量, 只有在这种情况下,这组输出才是有效的。我们分别记左,右括号的数量为left和right, 如下分析可看出,(()())是个有效的括号组合。

这样一来,在程序中,只要还有左括号,我们就加入输出串,然后递归调用。 当退出递归时,如果剩余的右括号数量比剩余的左括号数量多,我们就将右括号加入输出串。 直到最后剩余的左括号和右括号都为0时,即可打印一个输出串。代码如下:

完整代码如下:

 【原文参考】

剖析:

We can solve this problem recursively by recursing through the string   On each iteration, we have the index for a particular character in the string   We need to select either a left or a right paren   When can we use left, and when can we use a right paren?
» Left: As long as we haven’t used up all the left parentheses, we can always insert a left paren
» Right: We can insert a right paren as long as it won’t lead to a syntax error . When will we get a syntax error?  We will get a syntax error if there are more right parentheses than left
So, we simply keep track of the number of left and right parentheses allowed    If there are left  parens  remaining,  we’ll  insert  a  left  paren  and  recurse      If  there  are  more  right  parens remaining than left (eg, if there are more left parens used), then we’ll insert a right paren and recurse

 

猜你喜欢

转载自blog.csdn.net/u010982765/article/details/79988955