leetcode22 brackets generation

Topic : https://leetcode-cn.com/problems/generate-parentheses/

N represents the number of generation is given in parentheses, you write a function, it is possible to generate all possible combinations of brackets and effective.

Sample input and output :

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

Ideas :

  • Is not difficult to come up with the practice of direct violence, there is every position "(" and ")" two options, a total of 2 ^ n case. However, the number can be optimized, as must be the first bracket "(", and only in the "(" to be placed when ")", thus recording the number of left parenthesis, right parenthesis each put a left bracket minus 1 when the left parenthesis is the number 0, the next position can not be placed right parenthesis.

Code :

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> ans;
        string str; str.resize(2*n);
        dfs(0, n, str, ans, 0);
        return ans;
    }
private:
    void dfs(int idx, int n, string& str, vector<string>& ans, int l){
        if(idx == 2*n){
            if(l == 0){
                ans.push_back(str);
            }
            return;
        }
        str[idx] = '('; dfs(idx+1, n, str, ans, l+1);
        if(l)
            {str[idx] = ')'; dfs(idx+1, n, str, ans, l-1); }
    }
};
  • Another search strategy, with reference to https://leetcode-cn.com/problems/generate-parentheses/solution/hui-su-suan-fa-by-liweiwei1419/ number of left and right brackets are necessarily n, right and left brackets The number of remaining as a state, the search strategy are: 1) when there are parentheses around the branch can produce 2) as long as the number of left parenthesis is greater than 0, you can generate the left branch 3) to generate the right branch, only strictly greater than the number of right parenthesis in order to produce the number of branches of the left parenthesis.

Guess you like

Origin www.cnblogs.com/patrolli/p/12243205.html