思路一
生成n=6的所有情况,然后判断这个情况是不是符合题目要求的情况.是的话加入结果链表.
一开始我尝试使用循环生成所有情况.这是n=3的情况.
public List<String> generateParenthesis_(int n) {
List<String> res = new ArrayList<>();
for (int i = 0; i < n * 2; i++) {
for (int j = i + 1; j < n * 2; j++) {
for (int k = j + 1; k < n * 2; k++) {
String temp = "";
for (int z = 0; z < n * 2; z++) {
if (z == i || z == j || z == k) temp += '(';
else temp += ')';
if (isValide(temp) && temp.length() == n * 2) res.add(temp);
}
}
}
}
return res;
}
但是当我想推广的时候,有点点卡壳.意识到可能需要用递归来生成才比较方便.不过递归写的比较少,还是很卡壳.然后就看了下官方题解.写出了自己版本的递归.
class Solution {
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<>();
allarray("", 0, n*2, res);
return res;
}
public void allarray(String s, int pos, int len, List<String> res) {
if (pos < len) {
allarray(s + '(', pos + 1, len, res);
allarray(s + ')', pos + 1, len, res);
}
if (isValide(s)&&pos==len) res.add(s);
}
public boolean isValide(String s) {
int valid = 0;
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='(')valid++;
else valid--;
if (valid<0)return false;
}
return valid==0;
}
}
思路二
分析情况,直接生成符合目标的情况.或者说剪枝,跳过不合适的情况.
class Solution {
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<>();
allarray("", 0, n*2, res);
return res;
}
public void allarray(String s, int pos, int len, List<String> res) {
int left_num=0,valid=0;
for (int i = 0; i < s.length(); i++) {
if(s.charAt(i)=='('){
left_num++;valid++;}
else valid--;
}
if (pos < len&&valid>=0) {
if(left_num<len/2)
allarray(s + '(', pos + 1, len, res);
allarray(s + ')', pos + 1, len, res);
}
if (pos==len) res.add(s);
}
}