The idea of this question is to use backtracking and dfs. Design a dfs helper function with left and right input. Everytime when we add a left parentheses (, we subtract left by 1, and increase right by 1.
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution: defgenerateParenthesis(self, n: int) -> List[str]: res = [] self.permutation(res, "", n, 0) return res defpermutation(self, res, tmp, l, r): if l == r == 0: res.append(tmp) return if l > 0: self.permutation(res, tmp+ '(', l-1, r+1) if r > 0: self.permutation(res, tmp+ ')', l, r-1)