LeetCode 22. Generate Parentheses(生成括号)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jmspan/article/details/51450647

原题网址:https://leetcode.com/problems/generate-parentheses/

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

"((()))", "(()())", "(())()", "()(())", "()()()"

方法:深度优先搜索。

public class Solution {
    public void find(int remain, int left, int right, char[] parenthesis, List<String> results) {
        if (remain == 0) {
            results.add(new String(parenthesis));
            return;
        }
        if (left + 1 <= parenthesis.length/2) {
            parenthesis[parenthesis.length - remain] = '(';
            find(remain-1, left+1, right, parenthesis, results);
        }
        if (right + 1 <= parenthesis.length/2 && right < left) {
            parenthesis[parenthesis.length - remain] = ')';
            find(remain-1, left, right+1, parenthesis, results);
        }
    }
    public List<String> generateParenthesis(int n) {
        List<String> results = new ArrayList<>();
        find(n*2, 0, 0, new char[n*2], results);
        return results;
    }
}

可以简化:

public class Solution {
    private void find(char[] p, int len, int left, int right, List<String> results) {
        if (len == p.length) {
            results.add(new String(p));
            return;
        }
        if (left<p.length/2) {
            p[len] = '(';
            find(p, len+1, left+1, right, results);
        }
        if (left>right) {
            p[len] = ')';
            find(p, len+1, left, right+1, results);
        }
    }
    public List<String> generateParenthesis(int n) {
        List<String> results = new ArrayList<>();
        find(new char[n*2], 0, 0, 0, results);
        return results;
    }
}


阅读更多
换一批

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