Topic describes

Their thinking

  1. This topic adopts the idea of DFS.
  2. Whenever there are left open parentheses, the number of left open parentheses is -1, and DFS continues.
  3. When the length of the open parenthesis is less than the length of the parenthesis, the remaining number of the close parenthesis is -1, and DFS continues.

The implementation code

var generateParenthesis = function(n) {
    // Define the final result returned
    const res = [];
    dfs(n,n,' ');
    / / DFS function
    function dfs(Lremain,Rremain,str) {
        // If the length of the STR argument is 2n, the recursion is over
        if (str.length === 2*n) {
            res.push(str);
            return;
        }
        // If the left parenthesis is too large, place the left parenthesis in the recursion
        if (Lremain > 0) {
            dfs(Lremain-1,Rremain,str+'(')}if (Lremain < Rremain) {
            dfs(Lremain,Rremain-1,str+') ')}}return res;
};
Copy the code

revelation

Learn to use DFS concepts to solve the problem of traversing all situations.

Refer to the answer key

Leetcode-cn.com/problems/ge…