Generate Parentheses
medium
backtracking
recursion
strings
combinatorics
Given an integer n, return every well-formed parentheses string that uses exactly n pairs of parentheses.
Return the answers in the deterministic order produced by backtracking that always tries appending ( before ) whenever both choices are allowed.
Input / output
- Input:
n: int - Output:
string[]containing every valid combination in canonical backtracking order
Examples
n = 3returns["((()))","(()())","(())()","()(())","()()()"].n = 1returns["()"].n = 0returns[""]because there is exactly one valid sequence of zero pairs: the empty string.
Constraints
0 <= n <= 7
Target complexity
- The optimal approach should build only valid prefixes, not all
2^(2n)raw strings.
Follow-up How would you count the number of valid combinations without generating them all, or generate them iteratively instead of recursively?
Examples
Example 1
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Example 2
Input: n = 1
Output: ["()"]
Example 3
Input: n = 0
Output: [""]