括号生成

给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。

例如,给出 n = 3,生成结果为:

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

思路

n个括号,意味着有2n个字符,对2n个字符进行排列,一共有2的2n次方种,从这么多可能筛选出有效的排列

class Solution {
    public List generateParenthesis(int n) {
        List list = new ArrayList<>();
        char[] str = new char[2 * n];
        generate(list, str, 0);
        return list;

       
        
    }

    public void generate(List list, char[] str, int pos) {
        if (pos == str.length) {
            if (check(str)) {
                list.add(new String(str));
                
            }
            return ;
        }

        str[pos] = '(';
        generate(list, str, pos + 1);
        str[pos] = ')';
        generate(list, str, pos + 1);
        
    }

    public boolean check(char[] str) {
        int count = 0;
        for (int i = 0; i < str.length; i++) {
            if (str[i] == '(') {
                count++;

            }else {
                count--;
            }
            if (count < 0) {
                return false;
            }
        }
        
        return count == 0;

    }
}
class Solution {
    public List generateParenthesis(int n) {
        List list = new ArrayList<>();
        generate(list, 0, 0, "", n);

       return list;
        
    }

    public void generate(List list, int left, int right, String str, int n) {
        
        if (str.length() == 2 * n) {
            list.add(str);
            return;

        }

        if (left < n) {
            generate(list, left + 1, right, str + "(", n);
        }

        if (right < left) {
            generate(list, left, right + 1, str + ")", n);
        }
        
    }
}

你可能感兴趣的:(括号生成)