leetcode 22. 括号生成

暴力枚举

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> list = getAll(2 * n);
        List<String> result = new ArrayList<>();
        for (String item : list) {
            int value = 0;
            int len = item.length();
            for (int i = 0; i < len; i++) {
                value = value + getValue(item.charAt(i));
                if (value < 0) {
                    break;
                }
            }
            if (value == 0) {
                result.add(item);
            }
        }
        return result;
    }

    public int getValue(char c) {
        if (c == '(') {
            return 1;
        } else {
            return -1;
        }
    }

    public List<String> getAll(int n) {
        if (n == 1) {
            List<String> ret = new ArrayList<String>();
            ret.add("(");
            return ret;
        }
        List<String> list = getAll(n - 1);
        List<String> result = new ArrayList<String>();
        for (String p : list) {
            result.add(p + "(");
            result.add(p + ")");
        }
        return result;
    }
}
posted @ 2023-07-04 15:33  jrjewljs  阅读(5)  评论(0编辑  收藏  举报