22. Generate Parentheses(回溯)

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:

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





class Solution:
    def generateParenthesis(self, n: int) -> List[str]:

        res = []
        def batracking(path,l,r):
            if len(path) == n*2 and l == n and r==n:
                res.append(path)
            if len(path) > n*2 or l >n or r > n or r > l:
                return
            
            batracking(path+'(',l+1,r)
            batracking(path+')',l,r+1)
        
        batracking("",0,0)
        return res

 

 

 

  1. 插入数量不超过n

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

class Solution:
    def generateParenthesis(self, n: int) -> List[str]:

        res = []
        def backtrack(path,l,r):
            if l==r and len(path)==n*2:
                res.append(path)
                return
            if r > l or len(path)>2*n:
                return
            backtrack(path+'(',l+1,r)
            backtrack(path+')',l,r+1)
        backtrack("",0,0)
        return res

 

 

 

 

 

 

 

 

 

class Solution:
    def __init__(self):
        self.res = []
    def generateParenthesis(self, n: int) -> List[str]:

        def vaild(path):
            l = 0
            r = 0
            for ch in path:
                if ch == '(':
                    l+=1
                else:
                    r+=1
                if r>l:
                    return False
            return l == r

        def backtracking(path):
            if len(path) >2*n:
                return
            if vaild(path) and len(path) == 2*n:
                self.res.append(path)
                return 
            backtracking(path+'(')
            backtracking(path+')')
        backtracking("")
        return self.res

 

 

 

暴力回溯:

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

 

posted @ 2018-04-22 17:22  乐乐章  阅读(287)  评论(0编辑  收藏  举报