数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
示例 1:
输入:n = 3
输出:["((()))","(()())","(())()","()(())","()()()"]
示例 2:
输入:n = 1
输出:["()"]
提示:
1 <= n <= 8
上代码:
-(NSArray *)generateParenthesis {
int n = 3;
NSMutableArray *list = [NSMutableArray new];
return [self getParenthesis:list left:0 right:0 n:n result:@""];
}
-(NSArray *)getParenthesis:(NSMutableArray *)list left:(int)left right:(int)right n:(int)n result:(NSString *)result {
if (left == n && right == n) {
[list addObject:result];
return list;
}
if (left < n) {
[self getParenthesis:list left:left + 1 right:right n:n result:[NSString stringWithFormat:@"%@%@",result,@"("]];
}
if (left > right && right < n) {
[self getParenthesis:list left:left right:right + 1 n:n result:[NSString stringWithFormat:@"%@%@",result,@")"]];
}
return list;
}
leetcode链接:力扣