这是我最近遇到的问题。
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
这是我的代码:
- (void)generateParentheses:(int)n{
for (int i = 1; i <= n; i++) {
[self generateParentheses:@"" open:0 close:0 pairs:i];
}
}
- (void)generateParentheses:(NSString *)output open:(int)open close:(int)close pairs:(int)pairs{
if ((open == pairs) && (close == pairs)) {
NSLog(@"%@",output);
}
else {
if (open < pairs) {
output = [output stringByAppendingString:@"("];
[self generateParentheses:output open:open+1 close:close pairs:pairs];
}
if (close < open) {
output = [output stringByAppendingString:@")"];
[self generateParentheses:output open:open close:close+1 pairs:pairs];
}
}
}
这里是当n=2时的结果
()
(())
(()()
当 n = 3 时,有很多不合式的括号。 我用debug的时候发现open=1,close =0的时候输出的是@"(("。很奇怪,不知道为什么,为什么不是@"("?
最佳答案
如果open < pairs
和 close < open
在你的函数中,然后你修改 output
在第一个条件表达式中(在到达第二个条件表达式之前附加“(”)。
要解决此问题,只需删除对 output
的分配即可然后放[output stringByAppendingString:@"("]
直接在方法调用中。
关于ios - Objective-C:生成括号的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32260510/