f(n)="("+f(n-1)+")
+f(i)f(n-i)
+f(n-i)f(i)
举个例子:
f(2)="("+f(1)+")"
+"()"f(1)
+f(1)"()"
1 import java.util.ArrayList; 2 import java.util.HashSet; 3 import java.util.List; 4 import java.util.Set; 5 6 public class Solution { 7 static public List<String> generateParenthesis(int n) { 8 Set<String>[] al = new Set[n + 1]; 9 for (int i = 0; i < al.length; i++) al[i] = new HashSet<>(); 10 al[1].add("()"); 11 Set<String> set=dp(n, al); 12 ArrayList<String>ans=new ArrayList<>(set.size()); 13 for (String s:set) ans.add(s); 14 return ans; 15 } 16 17 static Set<String> dp(int n, Set<String>[] al) { 18 if (al[n].size() != 0) return al[n]; 19 20 Set<String> a1 = dp(n - 1, al); 21 for (String s : a1) al[n].add("(" + s + ")"); 22 23 for (int i = 1; i <= n / 2; i++) { 24 Set<String> a2 = dp(i, al); 25 Set<String> a3 = dp(n - i, al); 26 27 for (String s1:a2){ 28 for (String s2:a3){ 29 al[n].add(s1+s2); 30 al[n].add(s2+s1); 31 } 32 } 33 } 34 return al[n]; 35 } 36 }