022 Bracket generation

LeetCode 22nd question bracket generation

Given that n represents the logarithm of generating parentheses, please write a function that generates all possible and valid parenthesis combinations.
For example, given n = 3, the resulting result is:
[
"((()))",
"(()())",
"(())()",
"()(())",
" ()()()”
]

method one

Use brute force method to list all parentheses, and then judge whether they conform to the rules of parenthesis generation.
Here we use a recursive function. The function firstly judges whether the length of the currently generated parentheses is reached n*2, if the length meets the requirements, judges whether it meets the parenthesis generation rules, if so, add it, otherwise discard
If length does not reach n*2, add ' (' and ')', recursive code.
When judging whether it complies with the bracket generation rules, a balance factor is used. If it is '(', balance is incremented, if it is ')', balance is decremented. It should be noted that if balance is less than zero, it will return false directly. is because it avoids situations like ")("

Java

    public List<String> generateParenthesis(int n) {
        List<String> result = new ArrayList<>();
        generateAll(new char[n * 2], 0, result);
        return result;
    }

    public void generateAll(char[] current, int pos, List<String> result) {
        if (pos == current.length) {
            if (valid(current)) {
                result.add(new String(current));
            }
        } else {
            current[pos] = '(';
            generateAll(current, pos + 1, result);
            current[pos] = ')';
            generateAll(current, pos + 1, result);
        }
    }

    public boolean valid(char[] current) {
        int balance = 0;
        for (char c : current) {
            if (c == '(') {
                balance++;
            } else {
                balance--;
            }
            if (balance < 0)
                return false;/// 防止类似于“)(”这种情况
        }
        return (balance == 0);
    }

C++

small issue

In the process of converting Java code to C++, we encountered such a problem: the length of the char current[] string array can be directly calculated in Java, but in C++, we can only use the sizeof() function or strlen() function to find its length.
sizeof() can find its length, but when we pass in char current[] void generateAll(char current[],int pos,vector<string>& result), the current at this time becomes a pointer, and the length obtained by using sizeof() is always 4.
strlen() finds its length, strlen() gets the direct length from the first character to '\0', if there is '\0' in the string, then the length we get is wrong.

Solution

Use strlen() to find its length, and add some characters to it when char current[] is initialized, as follows:

for(int i=0; i<n*2; i++)
  current[i]='*';
  current[n*2]='\0';

In this way, the problem has been successfully solved, and of course, if you have a better way, you can also communicate with each other.
Below is the complete code in C++.

class Solution
{
public:
    vector<string> generateParenthesis(int n)
    {
        vector<string> result = vector<string>();
        char current[n*2+1];
        for(int i=0; i<n*2; i++)
            current[i]='*';
        current[n*2]='\0';
        generateAll(current,0,result);
        return result;
    }
    void generateAll(char current[],int pos,vector<string>& result)
    {
        if(strlen(current)==pos)
        {
            if(valid(current))
            {
                result.push_back(current);
            }
        }
        else
        {
            current[pos]='(';
            generateAll(current,pos+1,result);
            current[pos]=')';
            generateAll(current,pos+1,result);
        }
    }
    bool valid(char current[])
    {
        int balance=0;
        for(int i=0; i<strlen(current); i++)
        {
            if(current[i]=='(')
                balance++;
            else
                balance--;
            if(balance<0)
                return false;
        }
        return (balance==0);
    }
};

Python

In the python code, I encountered such a problem: the final output result, the result in the result is the same, as shown in the following code, the output result is:[[")",")",")",")",")",")"],[")",")",")",")",")",")"],[")",")",")",")",")",")"],[")",")",")",")",")",")"],[")",")",")",")",")",")"]]

class Solution(object):
    def generateParenthesis(self, n):
        result = []
        current = ['0' for i in range(n * 2)]
        self.generateAll(current, 0, result)
        return result

    def generateAll(self, current, pos, result):
        if (len(current) == pos):
            if self.valid(current):
                result.append(current)
                print(result)
        else:
            current[pos] = '('
            self.generateAll(current, pos + 1, result)
            current[pos] = ')'
            self.generateAll(current, pos + 1, result)

    def valid(self, current):
        balance = 0
        for c in current:
            if (c == '('):
                balance = balance + 1
            else:
                balance = balance - 1
            if (balance < 0):
                return False
        return balance == 0

In the end, I had to change the code and pass in one more length parameter in the function, which successfully solved the problem. The code is as follows:

class Solution(object):
    def generateParenthesis(self, n):
        result = []
        self.generateAll("", n, 0, result)
        return result

    def generateAll(self, current, n, pos, result):
        if (n*2 == pos):
            if self.valid(current):
                result.append(current)
        else:
            current_1 = current + '('
            self.generateAll(current_1, n, pos + 1, result)
            current_2 = current + ')'
            self.generateAll(current_2, n, pos + 1, result)

    def valid(self, current):
        balance = 0
        for c in current:
            if (c == '('):
                balance = balance + 1
            else:
                balance = balance - 1
            if (balance < 0):
                return False
        return balance == 0

Method Two

Because the qualified parenthesis sequence, the left parenthesis and the parenthesis are equal, and the existing left parenthesis is followed by a right parenthesis. According to this feature, we directly combine according to its characteristics during the traversal process.

Java

    public List<String> generateParenthesis(int n) {
        List<String> result = new ArrayList<>();
        backTrack(result, "", 0, 0, n);
        return result;
    }

    public void backTrack(List<String> result, String current, int open, int close, int n) {
        if (n * 2 == current.length()) {
            result.add(current);
        } else {
            if (open < n)
                backTrack(result, current + '(', open + 1, close, n);
            if (close < open)
                backTrack(result, current + ')', open, close + 1, n);
        }

    }

C++

    vector<string> generateParenthesis(int n)
    {
        vector<string> result=vector<string>();
        backTrack(result,"",0,0,n);
        return result;
    }
    void backTrack(vector<string>& result,string current,int open,int close,int n)
    {
        if(n*2==current.length())
            result.push_back(current);
        else
        {
            if(open<n)
                backTrack(result, current+'(',open+1,close,n);
            if(close<open)
                backTrack(result,current+')',open,close+1,n);
        }
    }

Python

    def generateParenthesis(self, n):
        result = []
        self.backTrack(result, "", 0, 0, n)
        return result

    def backTrack(self, result, current, open, close, n):
        if n * 2 == len(current):
            result.append(current)
        else:
            if open < n:
                self.backTrack(result, current + '(', open + 1, close, n)
            if close < open:
                self.backTrack(result, current + ')', open, close + 1, n)

Method three

Method 3 is simpler and clearer, because the entire parenthesis expression is similar to "(" + left + ")" + rightthis form, that is, a left parenthesis first, followed by a right parenthesis, a part is added between the left parenthesis and the right parenthesis, and a part is added after the right parenthesis. According to this feature, The code can be written as follows.

Java

public List<String> generateParenthesis(int n) {
        List<String> result = new ArrayList<>();
        if (n == 0)
            result.add("");
        else
            for (int c = 0; c < n; c++)
                for (String left : generateParenthesis(c))
                    for (String right : generateParenthesis(n - 1 - c))
                        result.add("(" + left + ")" + right);
        return result;
    }

C++

    vector<string> generateParenthesis(int n)
    {
        vector<string>result=vector<string>();
        if(n==0)
            result.push_back("");
        else
            for(int c=0; c<n; c++)
            {
                vector<string> result_left=generateParenthesis(c);
                for(int i=0;i<result_left.size();i++)
                {
                    string left=result_left[i];
                    vector<string>result_right=generateParenthesis(n-1-c);
                    for(int j=0;j<result_right.size();j++)
                    {
                        string right=result_right[j];
                        result.push_back("("+left+")"+right);
                    }
                }
            }
        return result;
    }

python

    def generateParenthesis(self, n):
        result = []
        if n == 0:
            result.append("")
        else:
            for c in range(n):
                for left in self.generateParenthesis(c):
                    for right in self.generateParenthesis(n - 1 - c):
                        result.append("(" + left + ")" + right)
        return result

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324380844&siteId=291194637