34 lines
776 B
Java
34 lines
776 B
Java
/*
|
|
* @lc app=leetcode id=22 lang=java
|
|
*
|
|
* [22] Generate Parentheses
|
|
*/
|
|
|
|
// @lc code=start
|
|
class Solution {
|
|
public List<String> generateParenthesis(int n) {
|
|
List<String> r = new ArrayList<String>();
|
|
dfsGenParenthesis(r, "", 0, 0, n);
|
|
return r;
|
|
}
|
|
|
|
private void dfsGenParenthesis(List<String> r, String s, int i, int k, int n) {
|
|
if(i == n && k == 0) {
|
|
r.add(s);
|
|
return;
|
|
} else if(i > n) {
|
|
return;
|
|
}
|
|
if(i < n) {
|
|
String t = s + "(";
|
|
dfsGenParenthesis(r, t, i+1, k+1, n);
|
|
}
|
|
if(k > 0) {
|
|
String t = s + ")";
|
|
dfsGenParenthesis(r, t, i, k-1, n);
|
|
}
|
|
}
|
|
}
|
|
// @lc code=end
|
|
|