括号生成

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

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

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

思路

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

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

       
        
    }

    public void generate(List<String> 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<String> generateParenthesis(int n) {
        List<String> list = new ArrayList<>();
        generate(list, 0, 0, "", n);

       return list;
        
    }

    public void generate(List<String> 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);
        }
        
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 22. 括号生成 描述 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。...
    GoMomi阅读 359评论 0 0
  • 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。 例如,给出 n = 3...
    闭门造折阅读 108评论 0 0
  • 题目描述 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。 例如,给出 ...
    莫小鹏阅读 390评论 0 0
  • 给出n代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。 例如,给出n=3,生成结果...
    不爱去冒险的少年y阅读 195评论 0 0
  • Math对象 Math对象的属性属性说明Math.E自然对数的底数,就是eMath.LN1010的自然对数Math...
    谢谢_d802阅读 448评论 0 0