Backtracking Algorithm Practice: Generating Valid Parentheses
OriginalAbout 2017 words
This article will resolve
LeetCode | Difficulty |
---|---|
22. Generate Parentheses | 🟠 |
Prerequisites
Before reading this article, you need to learn:
Bracket problems can be divided into two types. One is checking if brackets are valid, which I have covered before. The other is generating valid parentheses. To check if brackets are valid, we usually use a stack. To generate all valid combinations, we often use backtracking to try all possible ways.
Now, let's look at LeetCode Problem 22: Generate Parentheses. The task is:
22. Generate Parentheses | LeetCode | 🟠
Given n
pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example 1:
Input: n = 3 Output: ["((()))","(()())","(())()","()(())","()()()"]
Example 2:
Input: n = 1 Output: ["()"]
Constraints:
1 <= n <= 8
The function signature is:
java
List<String> generateParenthesis(int n);
cpp
vector<string> generateParenthesis(int n);
python
def generateParenthesis(n: int) -> List[str]:
go
func generateParenthesis(n int) []string
javascript
var generateParenthesis = function(n) {};
For bracket problems, just remember the following key points and you will find the solution easily: