https://www.youtube.com/watch?v=SwyEvjkUnPU

https://leetcode.cn/problems/generate-parentheses/description/

https://www.nowcoder.com/feed/main/detail/d54350e96be941b68677dfe383fea98d

https://www.youtube.com/watch?v=SwyEvjkUnPU

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList();
        if (n == 0) return res;
        helper(res, "", n, n);
        return res;
    }

    public static void helper(List<String> res, String s, int left, int right) {
        if (left > right) {
            return;
        }

        if (left == 0 && right == 0) {
            res.add(s);
            return;
        }
        if (left > 0) {
            helper(res, s + "(", left - 1, right);

        }
        if (right > 0) {
            helper(res, s + ")", left, right - 1);
        }
    }
}
class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList();
        if(n == 0) return res;
        dfs(res, "", n, n);
        return res;
    }

    public static void dfs(List<String> res, String s, int left, int right) {
        if(left > right) {
            return;
        }

        if(left == 0 && right == 0) {
            res.add(s);
            return;
        }

        if(left > 0) {
            dfs(res, s + "(", left - 1, right);
        }

        if(right > 0) {
            dfs(res, s + ")", left, right - 1);
        }
    }
}

https://leetcode.cn/problems/generate-parentheses/solutions/35947/hui-su-suan-fa-by-liweiwei1419/

这一类问题是在一棵隐式的树上求解,可以用深度优先遍历,也可以用广度优先遍历。 一般用深度优先遍历。原因是: