核心代码是我在评论里看到一位小姐姐写的,没有找到代码链接,她的力扣id是"钰娘娘"。我在演草纸上代入数据试了试,牛的!
个人微改:
import java.util.*;
class Solution01{
List<String> res = new ArrayList<>();
public List<String> generateParentheses(int n){
if(n<=0) {
return res;
}
getParenthesis("",n,n);
return res;
}
public void getParenthesis(String str,int left,int right) {
if(left==0&&right==0) {
res.add(str);
return;
}
if(left==right) {
getParenthesis(str+"(",left-1,right);
}else if(left < right) {
if(left>0) {
getParenthesis(str+"(",left-1,right);
}
getParenthesis(str+")",left,right-1);
}
}
}
public class parathesesGenerate {
public static void main(String args[]) {
System.out.println("please enter your data :");
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
Solution01 hah = new Solution01();
hah.generateParentheses(m);
System.out.println(hah.res);
sc.close();
}
}
测试结果:
please enter your data :
3
[((())), (()()), (())(), ()(()), ()()()]