首页 > 学院 > 开发设计 > 正文

22. Generate Parentheses

2019-11-06 06:56:30
字体:
来源:转载
供稿:网友

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 class Solution { public List<String> generateParenthesis(int n) { List<String> res = new ArrayList<String>(); if(n < 1) return res; if(n == 1){ res.add("()"); return res; } List<String> PRe = generateParenthesis(n-1); HashSet<String> set = new HashSet<String>(); for(int i = 0; i < pre.size(); i++){ String str = pre.get(i); for(int j = 0; j <= str.length(); j++){ String first = str.substring(0, j); String last = str.substring(j, str.length()); set.add(first+"()"+last); } } for(String s : set){ res.add(s); } return res; }}public class Solution { public List<String> generateParenthesis(int n) { List<String> res = new ArrayList<String>(); char[] c = new char[n * 2]; helper(n, n, c, 0, res); return res; } public void helper(int left, int right, char[] c, int index, List<String> res){ if(index == c.length){ res.add(new String(c)); return; } if(left <= right && left > 0) { c[index] = '('; helper(left-1, right, c, index+1, res); } if(right > 0){ c[index] = ')'; helper(left, right-1, c, index+1, res); } }}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表