左右括号全排列

public class 左右括号全排列 {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int n = sc.nextInt();//括号数
        sc.close();
        StringBuffer sb = new StringBuffer();
        permutation(sb, n);
    } 
    private static void permutation(StringBuffer sb, int n) {
        if(sb.length() == 2 * n) {
            if(isLegal(sb)) {
                System.out.println(sb.toString());
            }
            return;
        }
        //增加后回溯
        sb.append('(');
        permutation(sb, n);
        sb.deleteCharAt(sb.length() - 1);
        sb.append(')');
        permutation(sb, n);
        sb.deleteCharAt(sb.length() - 1);
    }
    private static boolean isLegal(StringBuffer sb) {
        Stack stk = new Stack<>();
        int len = sb.length();
        for(int i = 0; i < len; i++) {
            if(sb.charAt(i) == '(') {
                stk.push(sb.charAt(i));
            }
            if(sb.charAt(i) == ')') {
                if(!stk.isEmpty() && stk.peek() == '(') {
                    stk.pop();
                }else {
                    return false;
                }
            }
        }
        return stk.isEmpty();
    } 
}

你可能感兴趣的:(全排列)