22. 括号生成 Generate Parentheses

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]

 

方法一:

递归+遍历。

申请2n长度的字符数组

每位分别赋值为左右括号,当长度为2n时判断是否合法

public List<String> generateParenthesis(int n) {
        List<String> ans = new ArrayList<>();
        generate(ans, new char[2 * n ], 0);
        return ans;
    }
    public void generate(List<String> ans, char[] cur, int n){
        if( n == cur.length)
        {
            if(valid(cur)){
                ans.add(new String(cur));
            }  
            return;
        }else{
            cur[n] = '(';
            generate(ans, cur, n + 1);
            cur[n] = ')';
            generate(ans , cur, n + 1);
        }

    }
    public boolean valid(char []cur){
        int balance = 0;
        for(char c: cur){
            if(c == '('){
                balance += 1;
            }else{
                balance -= 1;
            }
            if(balance < 0) return false;
        }
        return balance == 0;
    }

 

方法二:

     回溯法,添加左括号的规则是左括号数量小于n。添加右括号的规则是右括号小于左括号。

    当然方法一也可以增加添加括号规则。

public List<String> generateParenthesis(int n) {
        List<String> ans = new ArrayList<>();
        backtrack(ans, new StringBuilder(), 0 ,0 , n);
        return ans;
        
    }
    public void backtrack(List<String> ans, StringBuilder cur, int left, int right, int max){
        if(cur.length() == 2 * max){
            ans.add(cur.toString());
            return;
        }
        if (left < max){
            cur.append('(');
            backtrack(ans, cur, left + 1, right, max);
            cur.deleteCharAt(cur.length() - 1);
        }
        if( right < left ){
            cur.append(')');
            backtrack(ans, cur, left, right + 1, max);
            cur.deleteCharAt(cur.length() - 1);
        }
    }

 

参考链接:

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

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

上一篇:IDEA如何通过一个数据库连接快速生成实体类


下一篇:如何使用VisualStudio2015编译GDAL