码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode] Generate Parentheses

时间:2015-01-03 07:03:14      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:

题目:(Backtrancing)

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:

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

 

题解:

比较特殊的一条backingtrancing,其实也就是和我们的套路略有点出入

public class Solution {
    public ArrayList<String> generateParenthesis(int n) {
        ArrayList<String> list =new ArrayList<String>();
        generate(list,"",0,0,n);
        return list;
    }
    
    public void generate(ArrayList<String> list,String res,int leftNum,int rightNum,int n){
        //防错误的右边括号出现
        if(leftNum<rightNum)
           return ;
        if(leftNum==n&&rightNum==n){
            list.add(res);
            return ;
        }
        
        if(leftNum==n){
            generate(list,res+")",leftNum,rightNum+1,n);
            return ;
        }
        
         generate(list,res+"(",leftNum+1,rightNum,n);
         generate(list,res+")",leftNum,rightNum+1,n);
        
    }
}

 

[leetcode] Generate Parentheses

标签:

原文地址:http://www.cnblogs.com/fengmangZoo/p/4199073.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!