博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
实现一个算法打印出n对括号的有效组合
阅读量:4283 次
发布时间:2019-05-27

本文共 3173 字,大约阅读时间需要 10 分钟。

转载于: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

 

你可能感兴趣的文章
cf D. Bag of mice
查看>>
UVA 10519 !! Really Strange !!
查看>>
UVA 10910 Marks Distribution(组合数学 或 递推)
查看>>
nyoj - 概率计算 926
查看>>
nyoj-492 King(状态压缩)
查看>>
poj -- 2288 Islands and Bridges
查看>>
hdu-2209 翻纸牌游戏
查看>>
HDU 3001 Travelling
查看>>
poj 2411 && 2663 && 3420 && 点头1033
查看>>
hdu- 5015 233 Matrix
查看>>
nyoj-999 师傅又被妖怪抓走了
查看>>
ZOJ 2317 Nice Patterns Strike Back(矩阵快速幂)
查看>>
hdu-4686 Arc of Dream
查看>>
经典题目
查看>>
hdu-5068 Harry And Math Teacher
查看>>
鞍山邀请赛 部分题
查看>>
bnu- 34985 Elegant String
查看>>
hdu-4028 The time of a day
查看>>
hdu - 4027 Can you answer these queries?
查看>>
hdu - 2512 一卡通大冒险 (斯特灵数 && 贝尔数)
查看>>