题解 | #括号生成#
括号生成
https://www.nowcoder.com/practice/c9addb265cdf4cdd92c092c655d164ca
import java.util.*; public class Solution { /** * * @param n int整型 * @return string字符串ArrayList */ public ArrayList<String> generateParenthesis (int n) { // write code here ArrayList<String> result=new ArrayList<>(); if(n==0){ return result; } dfs(n,0,0,0,result,""); return result; } public void dfs(int n,int left,int right,int k,ArrayList<String> result,String str){ if(2*n==k){ result.add(str); } if(left<n){ dfs(n,left+1,right,k+1,result,str+"("); } if(right<n&&left>right){ dfs(n,left,right+1,k+1,result,str+")"); } } }