LeetCode #22 括号生成

22. 括号生成

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

 

示例 1:

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

示例 2:

输入:n = 1
输出:["()"]

 

提示:

  • 1 <= n <= 8

看到有的大佬用的DP,自己实在这方面欠缺太多,数据也不大直接搜,2^16次方,每个位置有‘(’和‘)’两种情况,最后判断,当然也可以剪枝,后面也附上了。

class Solution {
vector<string> out;
public:
    int pd(string str){
        int cnt = 0;
        for(int i = 0;i < str.size();i++){
            if(str[i] == '(') cnt++;
            else{
                cnt--;
                if(cnt < 0) return 0;
            }
        }
        if(cnt == 0) return 1;
        return 0;
    }
    void dfs(int index,string str,int n){
        if(index == n-1){
            if(pd(str)) out.push_back(str);
            return ;
        }
        dfs(index+1,str+"(",n);
        dfs(index+1,str+")",n);
    }
    vector<string> generateParenthesis(int n) {
        dfs(0,"(",2*n);
        return out;
    }
};

剪枝就是去除一定不可能的条件,也就是右括号出现的次数大于左括号,或者剩余的位置不够和左括号匹配直接可以结束。

class Solution {
vector<string> out;
public:
    // int pd(string str){
    //     int cnt = 0;
    //     for(int i = 0;i < str.size();i++){
    //         if(str[i] == '(') cnt++;
    //         else{
    //             cnt--;
    //             if(cnt < 0) return 0;
    //         }
    //     }
    //     if(cnt == 0) return 1;
    //     return 0;
    // }
    void dfs(int index,string str,int n,int cnt){
        if(cnt<0||cnt>=n-index) return ;
        if(index == n-1){
            // if(pd(str)) out.push_back(str);
            out.push_back(str);
            return ;
        }
        dfs(index+1,str+"(",n,cnt+1);
        dfs(index+1,str+")",n,cnt-1);
    }
    vector<string> generateParenthesis(int n) {
        dfs(0,"(",2*n,1);
        return out;
    }
};

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值