第十六周算法分析与设计:Generate Parentheses

问题描述:

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:
[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]

Subscribe to see which companies asked this question.

问题出自此处


解法思路:
这是一道关于backtracking的问题,题意是求n对括号的全排列,但要求排列要合法。
可以这样考虑:
停止条件:当字符串的长度为 2n ,即n对括号的时候,回溯停止并把得到的字符串加进vector中。
状态转换过程:假设当前得到的字符串为cur_str,当它比n小时(表示当前字符串还可以容纳至少一对”()“),则将cur_str+”(“进入下一个新的状态;如果cur_str关于上一个”(“的回溯完成后,可以加入对应于这个”(“的右括号即”)”,当然前提是右括号的个数要比左括号的个数要小才能存在对应的。

class Solution {
public:
    int l_used=0, r_used=0;
    vector<string> generateParenthesis(int n) {
        vector<string> result;
        permutation(result,"",0,0,0,n);
        return result;

    }
    void permutation(vector<string>&result, string cur_str, int l_used, int r_used, int len,int n) {
        if (len == n * 2){
            result.push_back(cur_str);
            return;
        }
        else{
            if (l_used < n){
                permutation(result, cur_str+"(", l_used+1, r_used, len+1,n);
            }
            if (r_used < l_used){
                permutation(result, cur_str+")", l_used, r_used+1, len+1,n);
            }
        }

    }

};

时间复杂度为 O(N)
还有个注意的问题。就是在进入状态转换函数之前不能先将字符串修改了!!!否则的话就会进入不了下个状态,只会得到一个结果。(n=3、4的时候是这样。。)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值