Original link: leetcode-cn.com/problems/ge…

Answer:

  1. Use recursion to generate pairs of parentheses.
  2. The way to determine whether parentheses are paired is as follows
    • Because the parentheses must be paired, the final number of left and right parentheses is the logarithm of the parentheses, that is, as long as the logarithm of the left and right parentheses is less than the logarithm, the parentheses can be inserted.
    • You can insert a close parenthesis only if the open parenthesis is greater than the close parenthesis. This guarantees that the left parenthesis will be inserted first, which ensures that the parentheses are paired. And the number of close parentheses is also less than the logarithm.
  3. When the length of the string is equal to logarithm *2, it indicates that the string has been generated, the result can be saved and the recursion can be terminated.
// Use recursion to generate pairs of parentheses
function generate(str, left, right, max, result) {
  // Recursive terminating condition
  // End the loop when the length of the generated string equals the maximum length
  if (str.length === max * 2) {
    // Since the string was generated with parentheses, only the result needs to be stored
    result.push(str);
    // End the recursion
    return;
  }

  // The current level of recursive logic and continue recursion.
  // When the left parenthesis is less than the logarithm, a further pair of parentheses can be generated
  // Add an open parenthesis. The closing bracket can be completed recursively again.
  // The number of open parentheses is increased by 1
  if (left < max) {
    generate(str + '(', left + 1, right, max, result);
  }

  // When the number of open parentheses is greater than that of close parentheses, close parentheses can be added to form a pair of parentheses
  // The number of close parentheses is increased by 1
  if (left > right) {
    generate(str + ') ', left, right + 1, max, result); }}/ * * *@param {number} n
 * @return {string[]}* /
var generateParenthesis = function (n) {
  let result = []; // Save the result

  // Use recursion to generate pairs of parentheses
  generate(
    ' '.// The initial string is empty
    0.// Open parenthesis count
    0.// Close bracket count
    n, // Parenthesis logarithms
    result, // Save the result
  );

  return result;
};
Copy the code