原题网址:https://leetcode.com/problems/generate-parentheses/
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 void find(int remain, int left, int right, char[] parenthesis, List results) {
if (remain == 0) {
results.add(new String(parenthesis));
return;
}
if (left + 1 <= parenthesis.length/2) {
parenthesis[parenthesis.length - remain] = '(';
find(remain-1, left+1, right, parenthesis, results);
}
if (right + 1 <= parenthesis.length/2 && right < left) {
parenthesis[parenthesis.length - remain] = ')';
find(remain-1, left, right+1, parenthesis, results);
}
}
public List generateParenthesis(int n) {
List results = new ArrayList<>();
find(n*2, 0, 0, new char[n*2], results);
return results;
}
}
可以简化:
public class Solution {
private void find(char[] p, int len, int left, int right, List results) {
if (len == p.length) {
results.add(new String(p));
return;
}
if (leftright) {
p[len] = ')';
find(p, len+1, left, right+1, results);
}
}
public List generateParenthesis(int n) {
List results = new ArrayList<>();
find(new char[n*2], 0, 0, 0, results);
return results;
}
}