题解 | #括号生成# 递归 + 条件补全
括号生成
https://www.nowcoder.com/practice/c9addb265cdf4cdd92c092c655d164ca
import java.util.*; public class Solution { public ArrayList<String> dpBuild(int n) { if (n == 1) { return new ArrayList<String>( Arrays.asList("()") ); } else if (n == 2) { return new ArrayList<String>( Arrays.asList("()()", "(())") ); } else { Set<String> result = new HashSet<String>(); for(int i = 1; i <= n-1; i++){ ArrayList<String> a = dpBuild(i); ArrayList<String> b = dpBuild(n-i); StringBuilder pbuider = new StringBuilder(); StringBuilder lbuider = new StringBuilder(); int k = i; while(k-- > 0){ pbuider.append("("); lbuider.append(")"); } String pre = pbuider.toString(); String last = lbuider.toString(); for(String aStr:a){ for(String bstr:b){ result.add(aStr + bstr); result.add(bstr + aStr); result.add(pre + bstr + last); } } } return new ArrayList<>(result); } } public ArrayList<String> generateParenthesis (int n) { // write code here ArrayList<String> result = dpBuild(n); return result; } }
模拟出单侧聚集 (((((((((((((((( 类似的条件