https://leetcode.com/problems/generate-parentheses/
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: [ "((()))", "(()())", "(())()", "()(())", "()()()" ]
class Solution {
public:
vector generateParenthesis(int n) {
}
};
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
def gen(n, usedLeftCntList, usedRightCntList, prevStrList):
if usedLeftCntList[0] + usedRightCntList[0] == n + n:
return prevStrList
newUsedLeftCntList = []
newUsedRightCntList = []
newPrevStrList = []
for i, s in enumerate(prevStrList):
if usedLeftCntList[i] < n:
# we can add a '('
newUsedLeftCntList.append(usedLeftCntList[i] +1)
newUsedRightCntList.append(usedRightCntList[i])
newPrevStrList.append(prevStrList[i] + '(')
if usedRightCntList[i] < n and usedRightCntList[i] < usedLeftCntList[i]:
newUsedLeftCntList.append(usedLeftCntList[i])
newUsedRightCntList.append(usedRightCntList[i] +1)
newPrevStrList.append(prevStrList[i] + ')')
return gen(n, newUsedLeftCntList, newUsedRightCntList, newPrevStrList)
if n == 0:
return []
return gen(n, [0,],[0,], ['',])