-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenerateParentheses.java
More file actions
33 lines (30 loc) · 960 Bytes
/
GenerateParentheses.java
File metadata and controls
33 lines (30 loc) · 960 Bytes
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
29
30
31
32
33
package com.cier.solution.array;
import java.util.ArrayList;
import java.util.List;
/**
* https://leetcode-cn.com/problems/generate-parentheses/
*/
public class GenerateParentheses {
/**
* Runtime: 1 ms, faster than 93.50% of Java online submissions for Generate Parentheses.
* Memory Usage: 36.4 MB, less than 99.93% of Java online submissions for Generate Parentheses.
* @param n
* @return
*/
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<>();
singleStr(result,"",0,0,n);
return result;
}
private void singleStr(List<String> result, String str,int left, int right, int n){
if (left == n && right == n) {
result.add(str);
}
if (left < n) {
singleStr(result,str + "(", left + 1,right,n);
}
if (right < left) {
singleStr(result, str + ")", left, right+1,n);
}
}
}