美文网首页Leetcode
LeetCode #22 括号生成

LeetCode #22 括号生成

作者: HU兔兔 | 来源:发表于2020-02-10 15:06 被阅读0次
class Solution {
public:
    map<string,int> hash={{"(",1},{")",-1}};
    bool canaddRight(string str){
        int i=0;
        string s;
        int j;
        for(j=0;j<str.size();j++){
            s=str.substr(j,1);
            i+=hash[s];
        }
        return i;
    }
    int count(string str){
        int i=0;
        string s;
        int j;
        for(j=0;j<str.size();j++){
            s=str.substr(j,1);
            i+=hash[s]==1?1:0;
        }
        return i;
    }
    vector<string> generateParenthesis(int n) {
        vector<string> ans;
        queue<string> p;
        if(n==0){
            return ans;
        }
        p.push("(");
        string s,s_;
        while(!p.empty()){
            s=p.front();
            if(s.size()==2*n-1){
                ans.push_back(s+")");
            }
            else{
                if(canaddRight(s)){
                    p.push(s+")");
                }
                if(count(s)<n){
                    p.push(s+"(");
                }
            }
            p.pop();
        }
        return ans;
    }
};

这道题基本上就是两种思路,遍历或者动态规划(状态转移),遍历是用时间换空间,遍历是用空间换时间(存储所有n小的状态来减少遍历)。

相关文章

  • a 递归

    1 括号生成(leetcode 22)

  • LeetCode-22. 括号生成

    参考:第7课-泛型递归、树的递归 LeetCode-22. 括号生成 22. 括号生成 数字 n 代表生成括号的对...

  • LeetCode 22. 括号生成

    1、题目 22. 括号生成 - 力扣(LeetCode) https://leetcode-cn.com/prob...

  • 22. 括号生成

    22. 括号生成[https://leetcode.cn/problems/generate-parenthese...

  • LeetCode-22-括号生成

    LeetCode-22-括号生成 题目 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且...

  • LeetCode:22. 括号生成

    问题链接 22. 括号生成[https://leetcode.cn/problems/generate-paren...

  • 22. 括号生成

    22. 括号生成 题目链接:https://leetcode-cn.com/problems/generate-p...

  • Leetcode 22 括号生成

    题目 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。 例如,给出 n ...

  • [LeetCode]22、括号生成

    题目描述 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。 例如,给出 ...

  • Leetcode 22 括号生成

    给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。例如,给出 n = 3,...

网友评论

    本文标题:LeetCode #22 括号生成

    本文链接:https://www.haomeiwen.com/subject/xtvaxhtx.html