LeetCode算法系列:22. Generate Parentheses

版权声明:由于一些问题,理论类博客放到了blogger上,希望各位看官莅临指教https://efanbh.blogspot.com/;本文为博主原创文章,转载请注明本文来源 https://blog.csdn.net/wyf826459/article/details/81952145

题目描述

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:

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

算法描述:

这个问题采用回溯法进行递归求解。

我们求解这一问题的规则可以描述为:在任一位置左括号的个数大于等于右括号的个数。

所以,我们就可以按照这个规则去求解:假设在位置k我们还剩余left个左括号和right个右括号,如果left>0,则我们可以直接在当前字符位置写‘(’,而不违背规则。能否添加右括号,我们还必须验证left和right的值是否满足规则,如果left>=right(实际上大于的情况永远不会出现),则我们不能添加右括号,因为会违反规则,否则可以打印右括号。如果left和right均为零,则说明我们已经完成一个合法字符串,可以将其加入到结果种。

算法实现:

class Solution {
public:
    void get(string s, int l, int r, vector<string> &res){
        if(r == 0 && l == 0) res.push_back(s);
        else if(l == 0 && r > 0){
            while(r > 0)
            {
                s += ')';
                r --;
            }
            res.push_back(s);
        }
        else if(l == r) {
            s += '(';
            get(s, l - 1, r, res);
        }
        else if(l < r){
            get(s + '(', l - 1, r, res);
            get(s + ')', l, r - 1, res);
        }
        
    }
    vector<string> generateParenthesis(int n) {
        vector<string> res;
        string s;
        get(s, n, n, res);
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/wyf826459/article/details/81952145
今日推荐