https://app.laicode.io/app/problem/66
Given N pairs of parentheses "()", return a list with all the valid permutations.
Assumptions
- N >= 0
Examples
- N = 1, all valid permutations are ["()"]
- N = 3, all valid permutations are ["((()))", "(()())", "(())()", "()(())", "()()()"]
- N = 0, all valid permutations are [""]
The number of parentheses should be >= 0.
DFS
E.g. N = 3
DFS process:
- How many levels are there? What does it store on each level?
- Six levels (3 pairs of parentheses).
- On each level, we only consider one position (only one parentheses can be added at this position)
- How many different states should we try on this level?
- Two states: "(" or ")"
The DFS helper function needs to take in 4 parameters:
- a holder of the current combination of parentheses (may be a StringBuilder in this case)
- l (number of "(" added so far)
- r (number of ")" added so far)
- a result list
The number of of ")" added so far can never exceeds the number of "(". When l < n, we can keep adding "(" and then ")".
public class Solution {
public List<String> validParentheses(int n) {
// Write your solution here
List<String> result = new ArrayList<>();
if (n <= 0) {
return result;
}
permute(new StringBuilder(), n, n, result);
return result;
}
private void permute(StringBuilder parentheses, int left, int right,
List<String> result) {
// Base case: when all n pairs of () have been added
if (left == 0 && right == 0) {
result.add(parentheses.toString());
return;
}
// Case 1: when there are still ( left
if (left > 0) {
parentheses.append('(');
// Go to the next level
permute(parentheses, left - 1, right, result);
// Backtracking
parentheses.deleteCharAt(parentheses.length() - 1);
}
// Case 2: when there are more ) than ( left
if (right > left) {
parentheses.append(')');
permute(parentheses, left, right - 1, result);
parentheses.deleteCharAt(parentheses.length() - 1);
}
}
}
There are n pairs of parentheses, so the recursion tree will have 2n levels. We need to consider two states (add "(" or ")") on each level ⇒ O(2^(2n)) ⇒ O(4^n) ⇒ we can still think it is O(2^n)
There are 2n levels in the recursion tree. Only a StringBuilder is used in each level ⇒ O(2n)