Original link: leetcode-cn.com/problems/ge…
Answer:
- Start by recursively generating all possible parentheses.
- Each level of recursion corresponds to two possibilities, left and right parentheses, and counts the length of the currently generated string.
- After generating a string of the appropriate length, filter out valid parentheses and store them into the result.
// Verify that the string is valid
function isValid(str) {
let count = 0; // Use the variable count to determine whether there are pairs of parentheses
// Iterate over all characters
for (const char of str) {
// When an open parenthesis is encountered, count the number
if (char === '(') {
count++;
} else {
// If the number of open parentheses is 0, the parentheses are not paired
if(! count) {return false;
}
// When a close parenthesis is encountered, if the left parenthesis has a count, one is cancelled outcount--; }}// If the traversal is complete, the count is 0, indicating that the parentheses are paired
return! count; }// Generate all possible strings recursively
function generate(str, max, result) {
// Recursive terminating condition:
// 1. The generated string reaches the maximum value
if (str.length === max) {
// 2. Verify that the parentheses are valid
if (isValid(str)) {
// Store the valid parentheses into the result
result.push(str);
}
// Exit the loop when the generated string reaches its maximum length
return;
}
// Current layer logic
// The current generated string has two possibilities: left and right parentheses
let str1 = str + '(';
let str2 = str + ') ';
// Go to the next level of recursion
generate(str1, max, result);
generate(str2, max, result);
}
/ * * *@param {number} n
* @return {string[]}* /
var generateParenthesis = function (n) {
let result = []; // Store the result
// Generate all possible parentheses recursively, and filter out valid parentheses
generate(
' '.// The initial string is empty
n * 2.// The length of the generated string
result, // Store the result
);
return result; // Return the result
};
Copy the code