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:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

 22. Generate Parentheses(回溯)

 

暴力回溯:

class Solution {
public:
    vector<string> res;
        bool is_vilid(const string& str) {
        int balance = 0;
        for (char c : str) {
            if (c == '(') {
                ++balance;
            } else {
                --balance;
            }
            if (balance < 0) {
                return false;
            }
        }
        return balance == 0;
    }

    void dfs(string& path,int level,int n) {
         if (level>n ) { 
             return;
         }    
        if (level==n ) {
            if (is_vilid(path)) res.emplace_back(path);
            return;
        }
        string path_back = path;
        path.append("(");
        dfs(path,level+1,n);
        path.pop_back();

        path.append(")");
        dfs(path,level+1,n);
        path.pop_back();
        
    }
    vector<string> generateParenthesis(int n) {
        string path = "";
        dfs(path,0,n*2);
        return res;
    }
};

 

 

 

 

class Solution {
public:
    vector<string> res;

    void dfs(string& path,int left, int right, int level,int n) {
         if (level>n || right > left || left>n/2||right>n/2) { 
             return;
         }    
        if (level==n &&left==right) {
            res.emplace_back(path);
            return;
        }
        string path_back = path;
        path.append("(");
        dfs(path,left+1,right,level+1,n);
        path.pop_back();

        path.append(")");
        dfs(path,left,right+1,level+1,n);
        path.pop_back();
        
    }
    vector<string> generateParenthesis(int n) {
        string path = "";
        dfs(path,0,0,0,n*2);
        return res;
    }
};

 

 

思路:向string 中插入( 和 ),每插入一个就减1。 那么如何保证这个combination 是正确的呢?

  1. 插入数量不超过n

  2. 可以插入 ) 的前提是 ( 的数量大于 )

所以就得到了递归的两个条件。

 1 class Solution(object):
 2     def generateParenthesis(self, n):
 3         """
 4         :type n: int
 5         :rtype: List[str]
 6         """
 7         res = []
 8         def help(s,left,right):
 9             if(left==0 and right==0):
10                 res.append(s[:])
11                 return 
12             if left>0:
13                 help(s+'(',left-1,right)
14             if right>left:
15                 help(s+')',left,right-1)
16         help('',n,n)
17         return res

 

相关文章: