Generate Parentheses的解法

11 篇文章 0 订阅

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 static List<String> generateParenthesis(int n) {
		
		Set<String> set = new HashSet<String>();
		StringBuilder sb = new StringBuilder();
		while(n -- > 0) {
			sb.append("()");
		}
		String s = sb.toString();
		
		generateParenthesis(set, s.toCharArray(), s.length() - 1, false);
		return new ArrayList<String>(set);
    }

	private static void generateParenthesis(Set<String> set, char[] s, int end, boolean isSkip) {
		String ns = new String(s);
		if(!set.contains(ns) || isSkip) {
			set.add(ns);
			int index = 0;
			if((index = ns.lastIndexOf(")(")) != -1 && end < index + 2) {
				generateParenthesis(set, s, index + 2, true);
			}
			
			for(int i = end; i >= 1; i--) {
				if(s[i] =='(' && s[i - 1] ==')') {
					s[i] = ')'; s[i-1] = '('; 
					generateParenthesis(set, s, i - 1, false);
					s[i] = '('; s[i-1] = ')';
				}
			}
		}
	}
别人的代码
public List<String> generateParenthesis(int n) {
        List<String> list = new ArrayList<String>();
        backtrack(list, "", 0, 0, n);
        return list;
    }
    
    public void backtrack(List<String> list, String str, int open, int close, int max){
        
        if(str.length() == max*2){
            list.add(str);
            return;
        }
        
        if(open < max)
            backtrack(list, str+"(", open+1, close, max);
        if(close < open)
            backtrack(list, str+")", open, close+1, max);
    }
这个算法很有意思,别人的解法相当的不错,他是从创建的角度来思考的。这让我想起一句话:如果以出生的那一刻定义为拥有全部时间,那么每一刻我的时间都在流逝;如果以死亡的那一刻定义为拥有全部时间,那么每一刻我都在收获时间。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

李文区

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值