实现一个算法打印出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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值