22. Generate Parentheses

来源:互联网 发布:各种淘宝助理版本下载 编辑:程序博客网 时间:2024/05/29 15:01

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);        }    }}
0 0
原创粉丝点击