2025-05-17提交
This commit is contained in:
33
22.generate-parentheses.java
Normal file
33
22.generate-parentheses.java
Normal file
@@ -0,0 +1,33 @@
|
||||
/*
|
||||
* @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
|
||||
|
||||
Reference in New Issue
Block a user