22. Generate Parentheses
Asked at 35Amazon70Bloomberg67Microsoft65Google62Meta61Apple43Infosys61Zenefits100Walmart Labs93Grammarly83Zoho81ServiceNow79Avito74Huawei67Myntra64Samsung63TikTok63EPAM Systems60Oracle58Qualcomm58Dell57Adobe55Expedia54Morgan Stanley54eBay53Uber52Flipkart52ByteDance50Yandex46IBM44Intuit43Salesforce41Nvidia39tcs36Goldman Sachs28
Problem
Return every well-formed string of n pairs of parentheses.
Example: n = 3 → ["((()))","(()())","(())()","()(())","()()()"]
Constraints: n ≤ 8.
Add ( while open < n; add ) while close < open. These two rules generate exactly the valid strings.
""
"("
"((" "()"
"(()" ... "()("
"(())" "()()"
Complexity: O(Catalan(n) · n) ≈ O(4ⁿ/√n).
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
res = []
def bt(cur, op, cl):
if len(cur) == 2 * n:
res.append(cur)
return
if op < n:
bt(cur + "(", op + 1, cl)
if cl < op:
bt(cur + ")", op, cl + 1)
bt("", 0, 0)
return res
assert sorted(Solution().generateParenthesis(3)) == sorted(["((()))", "(()())", "(())()", "()(())", "()()()"])
assert Solution().generateParenthesis(1) == ["()"]
assert sorted(Solution().generateParenthesis(4)) == ['(((())))', '((()()))', '((())())', '((()))()', '(()(()))', '(()()())', '(()())()', '(())(())', '(())()()', '()((()))', '()(()())', '()(())()', '()()(())', '()()()()']
class Solution {
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<>();
bt(n, new StringBuilder(), 0, 0, res);
return res;
}
private void bt(int n, StringBuilder cur, int op, int cl, List<String> res) {
if (cur.length() == 2 * n) { res.add(cur.toString()); return; }
if (op < n) { cur.append('('); bt(n, cur, op + 1, cl, res); cur.deleteCharAt(cur.length() - 1); }
if (cl < op) { cur.append(')'); bt(n, cur, op, cl + 1, res); cur.deleteCharAt(cur.length() - 1); }
}
}
func generateParenthesis(n int) []string {
res := []string{}
var bt func(cur string, open, closed int)
bt = func(cur string, open, closed int) {
if len(cur) == 2*n {
res = append(res, cur)
return
}
if open < n {
bt(cur+"(", open+1, closed)
}
if closed < open { // only close what is open
bt(cur+")", open, closed+1)
}
}
bt("", 0, 0)
return res
}