首页 > 代码库 > 生成n对括号的合法全排列

生成n对括号的合法全排列

 1 import java.util.Scanner; 2 import java.util.Stack 3 public class Main { 4     public static void main(String []args){ 5         Scanner sc =new Scanner(System.in); 6         while(sc.hasNext()){ 7             int m =sc.nextInt(); 8             Stack<String> s  =new Stack<String>(); 9             String n ="";10             generate(m , m, n);11         }12     }          13     public static void generate(int leftNum,int rightNum,String s)  14     {  15         if(leftNum==0&&rightNum==0)  16         {  17             System.out.println(s);  18         }  19         if(leftNum>0)  20         {  21             generate(leftNum-1,rightNum,s+‘(‘);  22         }  23         if(rightNum>0&&leftNum<rightNum)  24         {  25             generate(leftNum,rightNum-1,s+‘)‘);  26         }  27     }  28 }

 

生成n对括号的合法全排列