LeetCode刷题经验总结记录--22. 括号生成

https://leetcode-cn.com/problems/generate-parentheses/

数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。

示例:

输入:n = 3
输出:["((()))","(()())","(())()","()(())","()()()"]

解法

package leetcode2;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

/**
 * 2021/3/10 15:48
 *
 * @Author ayue
 */
public class Solution22 {
    public List<String> generateParenthesis(int n) {
        List<String> res = new LinkedList<String>();
        if (n <= 0) {
            return res;
        }
        comb(res, 0, new StringBuilder(), n);
        return res;
    }
    
    private void comb(List<String> res, int depth, StringBuilder stringBuilder, int n) {
        if (depth == n * 2) {
            String s = stringBuilder.toString();
            if (isValid(s)) {
                res.add(s);
            }
            return;
        }
        stringBuilder.append("(");
        comb(res, depth + 1, stringBuilder, n);
        stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        stringBuilder.append(")");
        comb(res, depth + 1, stringBuilder, n);
        stringBuilder.deleteCharAt(stringBuilder.length() - 1);
    }
    
    private boolean isValid(String s) {
        Stack<Character> stack = new Stack<Character>();
        for (int i = 0; i < s.length(); ++i) {
            if (s.charAt(i) == '(') {
                stack.push('(');
            } else {
                if (stack.isEmpty() || stack.pop() != '(') {
                    return false;
                }
            }
        }
        return stack.isEmpty();
    }
    
    public boolean valid2(char[] current) {
        int balance = 0;
        for (char c : current) {
            if (c == '(') {
                ++balance;
            } else {
                --balance;
            }
            if (balance < 0) {
                return false;
            }
        }
        return balance == 0;
    }
    
    
    public List<String> generateParenthesis2(int n) {
        List<String> combinations = new ArrayList<>();
        generateAll(new char[2 * n], 0, combinations);
        return combinations;
    }
    
    public void generateAll(char[] current, int pos, List<String> result) {
        if (pos == current.length) {
            if (valid2(current)) {
                result.add(new String(current));
            }
        } else {//在0位置先放'(',然后递归走放后面的括号,走完了跳出递归后,接着将0位置换成')',继续走递归放后面的括号。
            current[pos] = '(';
            generateAll(current, pos + 1, result);
            current[pos] = ')';
            generateAll(current, pos + 1, result);
        }
    }
    
    public List<String> generateParenthesis3(int n) {
        List<String> res = new LinkedList<String>();
        comb2(res, n, new StringBuilder(), 0, 0);
        return res;
    }
    
    private void comb2(List<String> res, int n, StringBuilder stringBuilder, int open, int close) {
        //方法1的变种,只是只在序列保持有效时才继续后面的括号添加,降低复杂度
        if (stringBuilder.length() == 2 * n) {
            res.add(stringBuilder.toString());
            return;
        }
        if (open < n) {
            stringBuilder.append('(');
            comb2(res, n, stringBuilder, open + 1, close);
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        }
        if (close < open) {
            stringBuilder.append(')');
            comb2(res, n, stringBuilder, open, close + 1);
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        }
    }
    
    ArrayList[] cache = new ArrayList[100];
    
    public List<String> generate(int n) {
        if (cache[n] != null) {
            return cache[n];
        }
        ArrayList<String> ans = new ArrayList<String>();
        if (n == 0) {
            ans.add("");
        } else {
            for (int c = 0; c < n; ++c) {
                for (String left : generate(c)) {
                    for (String right : generate(n - 1 - c)) {
                        ans.add("(" + left + ")" + right);
                    }
                }
            }
        }
        cache[n] = ans;
        return ans;
    }
    
    public List<String> generateParenthesis4(int n) {
        return generate(n);
    }
    
    
    public static void main(String[] args) {
        Solution22 solution22 = new Solution22();
        List<String> res = solution22.generateParenthesis4(3);
        System.out.println(res.toString());
    }
}

问题:主要还是对于递归的理解不够透彻

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值