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

Leetcode22. Generate Parentheses

时间:2015-04-03 12:51:34      阅读:116      评论:0      收藏: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:

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

 

solution:DFS模版

package leetcode2;

import java.util.ArrayList;

public class Generate_parenthese {
    public static ArrayList<String> generateParenthesis(int n) {
        ArrayList<String> reArrayList=new ArrayList<String>();
        String s=new String();
        dfs(reArrayList,s,n,n); //DFS的模版递归 dfs(list<E>,E,deep,somethingConstant)
        return reArrayList;
    }

   public static void dfs(ArrayList<String> reArrayList, String s, int left,int right) {
        // TODO Auto-generated method stub
        // 先考虑deep极值,此处为left,right个数,直接return
       if(right<left){
           return;
       }
       if(left==0&&right==0){  //当括号都用完时,将s存入list中
           reArrayList.add(s);
           return;
       }
       if(left>0){
           dfs(reArrayList, s+‘(‘, left-1, right);
       }
       if(right>0){
           dfs(reArrayList, s+‘)‘, left, right-1);
       }
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println(generateParenthesis(3));
    }

}

 

Leetcode22. Generate Parentheses

标签:

原文地址:http://www.cnblogs.com/joannacode/p/4389459.html

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