Problem
Problem page: https://leetcode.com/problems/generate-parentheses/
Topics: Backtracking, String
Difficulty: Medium
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:
"((()))", "(()())", "(())()", "()(())", "()()()"
Analysis
A common recursive backtracking problem, where opening and closing parentheses have to match. I only need one rule to check for a match: as I scan from left to right, the number of opening parentheses so far must be >= the number of closing parentheses. So at each level of recursion, I have two choices: add an opening parenthesis or add a closing parenthesis, but I can only continue down a branch if that choice keeps the counts within the rule. A branch ends once I've added n of each kind.
In the code, left_count tracks how many opening parentheses I've added so far. left_remain is the opening count minus the closing count, which gives me the number of opening parentheses I can still "use up". Adding two lists in Python joins them into one list, as in [1, 2] + [3] = [1, 2, 3].
Code
1 | class Solution: |
Article link: https://xnerv.wang/en/leetcode-generate-parentheses/
