JAVA DFS solution


  • 0
    T
    public List<String> generateParenthesis(int n) {
        List<String> result = new ArrayList<String>();
        Stack<String> stack = new Stack<String>();
        Stack<int[]> generate = new Stack<int[]>();
        stack.push("");
        generate.push(new int[]{n, 0});
        while (!stack.isEmpty()) {
            String s = stack.pop();
            int open = generate.peek()[0];
            int close = generate.pop()[1];
            if (open == 0 && close == 0)
                result.add(s);
            if (open > 0) {
                stack.push(s + "(");
                generate.push(new int[]{open - 1, close + 1});
            }
            if (close > 0) {
                stack.push(s + ")");
                generate.push(new int[]{open, close - 1});
            }
        }
        return result;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.