leetcode22 括号生成

leetcode22 括号生成

从本阶段开始按照专题刷lc。目前进行回溯(backTracking)的练习。

本题不难,基本是一个子集树的回溯思路,剪枝条件是能够构成有效括号组(用栈判定)和左右括号的数量都不会超过总数的一半。

代码:

class Solution {

    List<String> res = null;
    char[] x = null;
    int N = 0;
    int cntl = 0;
    int cntr = 0;

    // 检查到现在为止的结果是否可行
    private boolean check(int pos){
        Stack<Character> test = new Stack();
        test.push(x[1]);
        for(int i = 2;i <= pos;i++){
            if(!test.isEmpty() && test.peek() == ')'){
                return false;
            }else{
                if(x[i] == '(') test.push('(');
                if(x[i] == ')') {
                    if(!test.isEmpty())
                        test.pop();
                    else{
                        return false;
                    }
                }
            }
        }
        if(pos == N && test.isEmpty() || test.isEmpty() || pos < N && test.peek()=='(') 
            return true;
        return false;
    }

    void traceBack(int pos){
        if(pos > N){
            res.add(String.valueOf(x,1,N));
        }else{
            x[pos] = '(';
            cntl++; 
            if(check(pos) && cntl <= N/2 && cntr <= N/2){
                traceBack(pos+1);
            }
            cntl--;

            x[pos] = ')';
            cntr++;
            if(check(pos) && cntl <= N/2 && cntr <= N/2){
                traceBack(pos+1);
            }
            cntr--;
        }
    }

    public List<String> generateParenthesis(int n) {
        N = 2*n;
        res = new ArrayList();
        x = new char[500];
        traceBack(1);
        return res;
    }
}

6ms 38.4MB

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值