leetcode problem 22. Generate Parentheses

16 篇文章 0 订阅

Description

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

Solution

n对括号串可以拆分成几种情况:

  1. ( +n-1对括号串+ )
  2. i对括号串 + n-i对括号串
  3. n-i对括号串 + i对括号串

所以用递归

注意:

  1. 调用层数越少越好,i<=n/2
  2. 去掉重复元素
class Solution {
public:
    vector<string> combine(vector<string> p1, vector<string> p2)
    {
        vector<string> res;
        int l1(p1.size()),l2(p2.size());
        if(l1==l2)
        {
            for(int i = 0 ; i < l1 ; ++i)
                for (int j = 0 ; j <l2 ;++j)               
                    res.push_back(p1[i]+p2[j]);
        }
        else
        {
            for(int i = 0 ; i < l1 ; ++i)
                for (int j = 0 ; j <l2 ;++j)               
                {
                    res.push_back(p1[i]+p2[j]);
                    res.push_back(p2[j]+p1[i]);
                }
        }
        return res;
    }
    vector<string> generateParenthesis(int n) {
        int curLen;
        vector<string> res;
        if (n == 0) return res;
        if (n == 1) {
            res.push_back("()");
            return res;
        } 
        vector<string> curRes,curRes2;
        for(int i = 1 ; i <= n/2 ; ++i) 
        {
            curRes = generateParenthesis(i);
            if(n-i == i) curRes2=curRes;
            else curRes2 = generateParenthesis(n-i);
            curRes = combine(curRes,curRes2);
            res.insert(res.end(),curRes.begin(),curRes.end());
            if(i==1)
            {
                curLen = curRes2.size();
                for(int j = 0 ; j < curLen ; ++j) res.push_back("("+curRes2[j]+")");
            }
        }
        sort(res.begin(),res.end());   
        res.erase(unique(res.begin(), res.end()), res.end());
        return res;
    }
};

结果:

Runtime: 8 ms, faster than 98.05% of C++ online submissions for Generate Parentheses.
Memory Usage: 12 MB, less than 87.44% of C++ online submissions for Generate Parentheses.

20190402

tbc

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值