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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
思路:
1 回溯法
只有在我们知道序列仍然保持有效时才添加 '('
or ')'
。我们可以通过跟踪到目前为止放置的左括号和右括号的数目来做到这一点,
如果我们还剩一个位置,我们可以开始放一个左括号。 如果它不超过左括号的数量,我们可以放一个右括号。
class Solution { public List<String> generateParenthesis(int n) { List<String> ans = new ArrayList(); backtrack(ans, "", 0, 0, n); return ans; } public void backtrack(List<String> ans, String cur, int open, int close, int max){ if (cur.length() == max * 2) { ans.add(cur); return; } if (open < max) backtrack(ans, cur+"(", open+1, close, max); if (close < open) backtrack(ans, cur+")", open, close+1, max); } }
2 暴力法
将组合分成s1与s2。s1表示n-1个括号的组合,s2表示1个括号的组合,即”()“。将s2从头到尾插入s1中(用Set保存避免重复),结果即为n个括号的组合。
//generate parentheses public static List<String> generateParenthesis(int n){ List<String> res = new ArrayList<>(); if(n == 0){ return res; }else if(n == 1){ res.add("()"); }else{ Set set1 = new HashSet<>(); set1.add("()"); String s2 = "()"; for (int i = 2; i <= n; i++) { set1 = parenthesisTwo(set1,s2); if(i == n){ res.addAll(set1); } } } return res; } //两两组合 public static Set<String> parenthesisTwo(Set<String> set1,String s2){ Set<String> set = new HashSet<String>(); String s = ""; for (String s1 : set1) { set.add(s2+s1); for (int i = 1; i < s1.length(); i++) { s = s1.substring(0,i)+s2+s1.substring(i,s1.length()); set.add(s); } set.add(s1+s2); } return set; }