首页 > 其他 > 详细

LeetCode——Generate Parentheses

时间:2015-10-12 00:28:45      阅读:123      评论:0      收藏:0      [点我收藏+]

Description:

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:

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

参考:http://blog.csdn.net/yutianzuijin/article/details/13161721

 

public class Solution {
    
    public void solve(int left, int right, String ans, List<String> res) {
        
        if(left == 0 && right == 0) {
            res.add(ans);
        }
        
        if(left > 0) {
            solve(left-1, right, ans+"(", res);
        }
        
        if(right>0 && left<right) {
            solve(left, right-1, ans+")", res);
        }
        
        
    }
    
    public List<String> generateParenthesis(int n) {
        
        List<String> list = new ArrayList<String>();
        String ans = new String();
        solve(n, n, ans, list);
        
        return list;
    }
}

 

LeetCode——Generate Parentheses

原文:http://www.cnblogs.com/wxisme/p/4870407.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!