题解 | #括号生成#
括号生成
https://www.nowcoder.com/practice/c9addb265cdf4cdd92c092c655d164ca
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param n int整型 # @return string字符串一维数组 # class Solution: def generateParenthesis(self , n: int) -> List[str]: # write code here res = [] def recur(temp, nleft, nright): # 记录前面使用了多少左括号,右括号 if nleft == n: temp += ')'*(n-nright) res.append(temp) return # 递归函数一定要记得终止条件的return! if nleft > nright: # 这里不需要for,而且因为是str,在传入函数的时候改变,所以不需要自己再改变 recur(temp+'(', nleft+1, nright) recur(temp+')', nleft, nright+1) elif nleft == nright: recur(temp+'(', nleft+1, nright) recur('', 0, 0) return res