2.2 All permutations of parentheses II
Assumption: Given l pairs of (), m pairs of <>, and n pairs of {}, all pairs >= 0
Solution:
2l + 2m + 2n levels in the recursion tree, each level consider one position
states/branches: 2 * types of parentheses at most
Stop condition: when all parentheses are used
Additional restriction:
Same type, left added > right added
left must match the type of right. The right parenthesis must match the most recently unclosed left parenthesis.
Data structure:
Use 1 stack to pair match;
When adding a new left, check left_added, push into stack, add it to sb
When adding a new right, check if it matches stack.peek()
If matches, stack.pop(), add to sb
If not, skip this branch
private static final char[] PS = new char[]{'(', ')', '<', '>', '{', '}'};
public List<String> validParentheses(int l, int m, int n) {
int length = l * 2 + m * 2 + n * 2;
int[] remain = new int[] {l, l, m, m, n, n};
StringBuilder cur = new StringBuilder();
Deque<Character> stack = new LinkedList<>();
List<String> res = new ArrayList<>();
helper(cur, stack, remain, length, res);
return res;
}
private void helper(StringBuilder cur, Deque<Character> stack, int[] remain, int length, List<String> res) {
//base case
if (cur.length() == length) {
res.add(cur.toString());
return;
}
// i: index of char[] PS
for (int i = 0; i < remain.length; i++) {
if (i % 2 == 0) { //add a new left
if (remain[i] > 0) {
cur.append(PS[i]);
stack.offerFirst(PS[i]);
remain[i]--;
helper(cur, stack, remain, length, res);
remain[i]++;
cur.deleteCharAt(cur.length() - 1); //remove added parenthese
stack.pollFirst();
}
} else { //add a new right
if (!stack.isEmpty() && stack.peekFirst() == PS[i - 1]) {
cur.append(PS[i]);
stack.pollFirst();
remain[i]--;
helper(cur, stack, remain, length, res);
remain[i]++;
cur.deleteCharAt(cur.length() - 1);
stack.offerFirst(PS[i - 1]);
}
}
}
}
Previous2.3 All permutation of parentheses with priority restrictionNext2.1 All valid permutation of parentheses I
Last updated
Was this helpful?