1. 程式人生 > >[leetcode] 22. 括號生成

[leetcode] 22. 括號生成

gen 升級 com lis ++ leetcode ML esc 有效

22. 括號生成

謹慎後,1A的概率貌似高了些
算是20題的升級版吧,
利用遞歸來拼成string,然後通過20. 有效的括號該題的代碼來判斷生成的string合不合法

看代碼吧

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> ans = new ArrayList<>();
        dfs(ans, "", n, n);
        return ans;
    }

    public void dfs(List<String> list, String st, int left, int right) {
        if (left == 0 && right == 0 && isValid(st)) {
            list.add(st);
        }
        if (left > 0) dfs(list, st + "(", left-1, right);
        if (right > 0) dfs(list, st + ")", left, right-1);
    }

    public boolean isValid(String s) {
        Stack<Character> characterStack = new Stack<>();

        for (int i = 0; i < s.length(); i++) {
            switch (s.charAt(i)) {
                case ‘(‘:
                case ‘[‘:
                case ‘{‘:
                    characterStack.push(s.charAt(i));
                    break;
                case ‘)‘:
                    if (!characterStack.isEmpty() && characterStack.peek() == ‘(‘) {
                        characterStack.pop();
                        break;
                    } else {
                        return false;
                    }
                case ‘]‘:
                    if (!characterStack.isEmpty() && characterStack.peek() == ‘[‘) {
                        characterStack.pop();
                        break;
                    } else {
                        return false;
                    }
                case ‘}‘:
                    if (!characterStack.isEmpty() && characterStack.peek() == ‘{‘) {
                        characterStack.pop();
                        break;
                    } else {
                        return false;
                    }
            }
        }

        return characterStack.isEmpty();
    }
}

AC後觀摩榜單大神的代碼,發現其實不必使用isValid()函數判斷合法性,

只需保證已經生成的字符串中,左括號的數量>=右括號的數量即可,反過來講剩余待使用左括號數量要<剩余待使用的右括號數量,否則,當前分支剪掉,代碼如下

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> ans = new ArrayList<>();
        dfs(ans, "", n, n);
        return ans;
    }

    public void dfs(List<String> list, String st, int left, int right) {
        if (right < left) return;
        if (left == 0 && right == 0) {
            list.add(st);
        }
        if (left > 0) dfs(list, st + "(", left - 1, right);
        if (right > 0) dfs(list, st + ")", left, right - 1);
    }
}

尼瑪優化後居然比優化前慢5ms,嚴重懷疑leetcode評測機有毛病,代碼跑多久看RP

[leetcode] 22. 括號生成