自学内容网 自学内容网

面试算法-77-括号生成

题目

数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。

示例 1:

输入:n = 3
输出:[“((()))”,“(()())”,“(())()”,“()(())”,“()()()”]

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> result = new ArrayList<>();
        dfs(n, n, "", result);
        return result;
    }

    public void dfs(int left, int right, String path, List<String> result) {
        if (left == 0 && right == 0) {
            result.add(path);
        }

        if (left > right) {
            return;
        }
        if (left < 0) {
            return;
        }

        dfs(left - 1, right, path + "(", result);
        dfs(left, right - 1, path + ")", result);
    }
}

原文地址:https://blog.csdn.net/GoGleTech/article/details/136938080

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!