括号生成

问题

 

思路

1、回溯全遍历

2、不符合的及时剪枝

代码

 

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

public class Main {

    public static void main(String[] args) {
        Solution solution = new Solution();
        List<String> strings = solution.generateParenthesis(3);
        System.out.println(strings);
    }


    static class Solution {
        HashSet<String> res;
        HashSet<String> notRes;
        public List<String> generateParenthesis(int n) {
            res = new HashSet<>();
            notRes = new HashSet<>();
            StringBuilder str = new StringBuilder();
            for (int i = 0; i < n; i++) {
                str.append("()");
            }
            generateParenthesis(str.toString().toCharArray(), 0);
            return new ArrayList<>(res);
        }

        private void generateParenthesis(char[] str, int index) {
            if (notRes.contains(String.valueOf(str))){
                return;
            }
            int leftCount = 0;
            int rightCount = 0;
            for (int i = 0; i < index; i++) {
                if (str[i] == '('){
                    leftCount++;
                }else {
                    rightCount++;
                }
                if (rightCount > leftCount){
                    notRes.add(String.valueOf(str));
                    return;
                }
            }

            if (index == str.length - 1){
                res.add(String.valueOf(str));
            }
            for (int j = index; j < str.length; j++) {
                swap(j, index, str);
                generateParenthesis(str, index + 1);
                swap(index, j, str);
            }
        }

        private void swap(int index, int j, char[] str) {
            char temp = str[index];
            str[index] = str[j];
            str[j] = temp;
        }
    }


}

 

posted @ 2023-08-06 19:53  Adom_ye  阅读(8)  评论(0编辑  收藏  举报