leetcode22.括号生成

题目

给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。

例如,给出 n = 3,
生成结果为:

[ “((()))”, “(()())”, “(())()”, “()(())”, “()()()” ]

解题思路

我自己的思路首先的采用分治递归的方法,把每个问题都分为子问题(i)+(n-i)来解决,每次把子问题生成的括号相加,就是最终的结果,这个思路很容易想懂,不多解释。
看了一下别人的解题代码,是利用dfs去解答的。
记录左右括号的个数,如果左括号比右括号大,就加入一个右括号或左括号,当左括号右括号个数大于n的话说明这字符串不符合要求,return掉。

代码如下

自己的解法

class Solution {
    public List generateParenthesis(int n) {
        Set res = new HashSet<>();
        if(n == 1) {
        	res.add("()");
        }
        else {
        	for(int i = 1; i <= n/2; i ++) {
        		List list1 = generateParenthesis(i);
        		List list2 = generateParenthesis(n-i);
        		for(String s1: list1) {
        			for(String s2: list2) {
        				if(i==1) res.add("("+s2+")");
                		res.add(s1+s2);
                		res.add(s2+s1);
                	}
            	}
        	}
        }
        return new ArrayList<>(res);
    }
}

利用dfs解法

class Solution {
    public List generateParenthesis(int n) {
        List res = new ArrayList<>(1000);
        dfs(n, 0, 0, "", res);
        return res;
    }
	public void dfs(int n, int l, int r, String s, List list) {
		if(l > n || r > n) return;
		if(l ==n && r == n) list.add(s.toString());
		if(l >= r) {
			dfs(n, l+1, r, s + "(", list);
			dfs(n, l, r+1,  s + ")", list);
		}
	}
}

提交结果

成功
显示详情
执行用时 : 2 ms, 在Generate Parentheses的Java提交中击败了96.81% 的用户
内存消耗 : 37.7 MB, 在Generate Parentheses的Java提交中击败了73.49% 的用户

你可能感兴趣的:(算法,JAVA)