2017.10.20
f(n)的值就是在f(n-1)的基础上,遇到左括号就加一个(),然后再在开头加一个()
public class Solution {
/*
* @param n: n pairs
* @return: All combinations of well-formed parentheses
*/
public List<String> generateParenthesis(int n){
Set<String> set = generate(n);
List<String> res = new LinkedList<>();
for(String s :set){
res.add(s);
}
return res;
}
public Set<String> generate(int n){
// write your code here
Set<String> set = new HashSet<String>();
set.add("");
if(n == 0){
return set;
}
for(int i = 1; i <= n; i++){
Set<String> setTmp = new HashSet<String>();
for(String s : set){
setTmp.add("()" + s);
for(int j = 0; j < s.length(); j++){
if(Character.toString(s.charAt(j)).equals("(")){
String newString = s.substring(0, j+1) + "()" + s.substring(j+1);
setTmp.add(newString);
}
}
}
System.out.println("当n为" + i + "时,setTmp里的内容有:");
for(String s : setTmp){
System.out.print(s + ";");
}
System.out.println();
set.clear();
set.addAll(setTmp);
}
return set;
}
}