22. Generate Parentheses(Leetcode每日一题-2020.04.09)

Problem

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

Example1

Given n = 3, a solution set is:

[ “((()))”, “(()())”, “(())()”, “()(())”, “()()()” ]

Solution

经典回溯。

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> ret;
        if(n == 0)
            return ret;
        backtrack(n,n,"",ret);

        return ret;
        
    }

    void backtrack(int leftRemain,int rightRemain,string cur,vector<string> &ret)
    {
        if(leftRemain > rightRemain)
            return;
        if(leftRemain < 0 || rightRemain < 0)
            return;
        
        if(leftRemain == 0 && rightRemain == 0)
        {
            ret.push_back(cur);
            return;
        }

        if(leftRemain > 0)
        {
            backtrack(leftRemain - 1,rightRemain,cur+'(',ret);
        }

        if(rightRemain > 0)
        {
            backtrack(leftRemain,rightRemain - 1,cur+')',ret);
        }
 
发布了547 篇原创文章 · 获赞 217 · 访问量 56万+

猜你喜欢

转载自blog.csdn.net/sjt091110317/article/details/105422367