回溯但是先根遍历 leetcode 力扣 22 括号生成

53 阅读1分钟

1.jpeg

这不就是先根遍历吗?

left为当前结点左括号的数量right右括号的数量

处理叶子结点 如果当前结点left == right,将当前结点加入结果数组,并return

向左递归 如果当前结点left < n,向左递归。

向右递归 如果当前结点left > right,则允许向右递归。

class Solution {
    List<String> res = new ArrayList<>();

    public List<String> generateParenthesis(int n) {
        dfs("", 0, 0, n);
        return res;
    }

    public void dfs(String node, int left, int right, int n) {
        if (left == n && right == n) {
            res.add(node);
            return;
        }

        if (left < n) {
            dfs(node + "(", left + 1, right, n);
        }

        if (left > right) {
            dfs(node + ")", left, right + 1, n);
        }
    }
}