【LeetCode】22. 括号生成:深度优先搜索,dfs,剪枝,搜索回溯

在这里插入图片描述

这道题目可以使用dfs,即深度优先遍历。加上适当的剪枝。可以求解。搜索回溯。

class Solution {
    public List<String> generateParenthesis(int n) {
        // 这道题目采用深度优先遍历。适当的剪枝。
        List<String> res = new LinkedList<>();
        if (n == 0) return res;
        int remainLeft = n;
        int remainRight = n;
        StringBuffer path = new StringBuffer();
        dfs(res, remainLeft, remainRight, path);
        return res;
    }

    private void dfs(List<String> res, int remainLeft, int remainRight, StringBuffer path) {
        if (remainLeft == 0 && remainRight == 0) {
            res.add(new String(path));
            return;
        }

        // 进行遍历
        if (remainLeft > 0) {
            if ((remainLeft - 1) <= remainRight) {
                path.append("(");
                remainLeft--;
                dfs(res, remainLeft, remainRight, path);
                remainLeft++;
                path = path.deleteCharAt(path.length() - 1);
            }
        }
        if (remainRight > 0) {
            if (remainLeft <= (remainRight - 1)) {
                path.append(")");
                remainRight--;
                dfs(res, remainLeft, remainRight, path);
                remainRight++;
                path = path.deleteCharAt(path.length() - 1);
            }
        }
    }
}
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 书香水墨 设计师: CSDN官方博客
应支付0元
点击重新获取
扫码支付

支付成功即可阅读