22.Generate Parentheses [M] generated in brackets

topic

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:
 [
  "( ( ( ) ) )",
  "( ( ) ( ) )",
  "( ( ) ) ( )",
  "( ) ( ( ) )",
  "( ) ( ) ( )"
 ]


Thinking

Backtracking

For (n \) \ generate effective brackets, we can treat it as the following way:


Figure 1: a schematic diagram bracketed generated backtracking

In the figure, since the pair of brackets is always valid from "(" start, the root of the tree is "(." The number is referred to as a left parenthesis \ (L \) , is referred to as the number of right parenthesis \ (R & lt \) , a given number \ (n-\) , during the generation of the new brackets, divided into three cases

  • \ (L <n-\) , there are described the number of left parenthesis reaches a target value, should be increased left parenthesis
  • \ (L> R & lt \) , the number of right bracket described enough, it should generate a right parenthesis
  • \ (= n-R & lt \) , the instructions to complete \ (n-\) generates effective brackets.

Note that in this process, can not exceed the number of right parenthesis left parenthesis, if exceeded, not down recursively. This completes the backtracking process: recursion parentheses, but at the same time generating parentheses, brackets on check match. If it matches, recursively; If not, the down is not recursive. In a specific implementation, by ensuring that the right number of brackets \ (R & lt \) is always less than or equal to the number of left bracket achieve matching check.


Tips

Backtracking

The basic idea

The solution space problem into a graph or tree structure representation, then using the depth-first search strategy traversal, traverse the course record and find viable solutions and the optimal solution.

Basic behavior

The basic behavior is backtracking search, using two methods in the search process to avoid invalid search

  • 1. constraint functions, does not satisfy the constraints of the path cut
  • 2. defined conditions, the optimal solution can not be cut path
    backtracking is a way of thinking, is achieved through recursive or iterative In a specific implementation.

C++

 vector<string> generateParenthesis(int n) {
        
        vector<string> result;  
        
        if(n==0)
            return result;
        
        backTrack(result, "", 0, 0, n);
        
        return result;
    }
    
    void backTrack(vector<string> &res,string curStr,int l, int r, int n){
        
        if(r == n)
            res.push_back(curStr);
        
        //如果左括号没有达到给定的n
        if(l < n)
            backTrack(res, curStr+"(", l+1, r, n);
        
        //如果右括号数目不够
        if(r < l)
            backTrack(res, curStr+")", l, r+1, n);
    }

Python

reference

[1]
[2] https://blog.csdn.net/zjc_game_coder/article/details/78520742

Guess you like

Origin www.cnblogs.com/Jessey-Ge/p/10993515.html