【重点】【DFS】22.括号生成

题目

法1:DFS

必须掌握的方法!

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<>();
        char[] tmp = new char[n * 2];
        dfs(0, 0, 0, tmp, res);

        return res;
    }

    public void dfs(int curIndex, int left, int right, char[] tmp, List<String> res) {
        if (left < right || left > tmp.length / 2 || right > tmp.length / 2) {
            return;
        }
        if (curIndex == tmp.length) {
            res.add(String.valueOf(tmp));
            return;
        }

        if (left > right) {
            tmp[curIndex] = '(';
            dfs(curIndex + 1, left + 1, right, tmp, res);
            tmp[curIndex] = ')';
            dfs(curIndex + 1, left, right + 1, tmp, res);
        } else if (left == right) {
            tmp[curIndex] = '(';
            dfs(curIndex + 1, left + 1, right, tmp, res);
        }
    }
}

你可能感兴趣的:(力扣Top100,深度优先,括号生成)