22. Generate Parentheses

Recursion (My Solution)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<>();
for (int i = 0; i < n; i++) {
result = addParenthesis(result);
}

return result;

}

private List<String> addParenthesis(List<String> s) {
if (s.isEmpty()) {
return new ArrayList<>(Arrays.asList("()"));
}

Set<String> newSet = new HashSet<>();

for (String current : s) {
for (int i = 0; i <= current.length(); i++) {
String newStr = current.substring(0, i) + "()" + current.substring(i);
newSet.add(newStr);
}
}

return new ArrayList<>(newSet);
}
}

Remarks:

  1. TC $O(n!\times n)$
  2. Add new () to each gaps; will have duplication, use Set to remove.

Traceback

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<>();
backtrack(result, "", 0, 0, n);
return result;
}

private void backtrack(List<String> result, String current, int open, int close, int max) {
if (current.length() == max * 2) {
result.add(current);
return;
}

if (open < max) {
backtrack(result, current + "(", open + 1, close, max);
}
if (close < open) {
backtrack(result, current + ")", open, close + 1, max);
}
}
}

Remarks:

  1. TC $O(\cfrac{4^n}{\sqrt{n}})$
  2. From left to right, first add ( , then add )
  3. ( -> (( -> (() -> (()) -> ( -> ()()