Leetcode brushing record--22. Bracket generation (backtracking)

Foreword: I made another simple bracket generation today, only to find that I made a mistake when doing the backtracking problem last time. Backtracking is not equivalent to recursion. There will be a global variable in the backtracking method to save the current state. , And back to the previous state.
The number n represents the logarithm of generating parentheses. Please design a function for generating all possible and effective combinations of parentheses.

Examples:

输入:n = 3
输出:[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]

This question is not too difficult. I used the pair to judge the final state. The final state is 3 pairs of strings, but in fact this condition can be replaced with other better conditions, and it also saves the space of a haspair, such as Say to judge the length of the string, or to determine whether the number of left and right brackets have become n.
At the same time I used the idea of ​​backtracking, that is, to develop a global variable s to store the current string, but pay attention to Go back to the state of the previous node, so you need to go back, in this problem by deleting the last character of the string.
You can use this picture to understand:

State retreat is actually the process of returning from D to B

The specific implementation code is as follows:


class Solution {

string s ="";
public:
    vector<string> generateParenthesis(int n) {
        char symbol[2] = {'(',')'};
        vector<string> result;
        if(n == 0){
            result.push_back("");
            return result;
        }else{
            genSymbol(result, '(', 1, 0, 0, n);
            genSymbol(result, ')', 0, 1, 0, n);
            return result;
        }
        
    }


    void genSymbol(vector<string> &result, char symbol, int leftB, int rightB, int hasPair, int n ){
        
        if(hasPair == n){
            s += ')';
            result.push_back(s);
            s.pop_back();
            return;
        }else{
             s += symbol;
            if(leftB < n){
                // cout << s << " " << hasPair<< "   "<< leftB<<" " << rightB<< endl;
                genSymbol(result, '(', leftB+1, rightB, hasPair, n);
            }
            if(leftB > rightB){

                // cout << s << " " << hasPair+1<< "   "<< leftB<<" " << rightB<< endl;
               
                genSymbol(result, ')', leftB, rightB+1, hasPair+1, n);
               
            }
            
            s.pop_back();

        }
    }
};

In fact, there is still room for optimization in memory consumption ~

Guess you like

Origin www.cnblogs.com/yuyuan-bb/p/12756327.html