LeetCode-22. Generate Parentheses

Description

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

Example

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

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

Solution 1(C++)

class Solution{
public:
    vector<string> generateParenthesis(int n) {
        vector<string> res;
        helper(res, "", n, 0);
        return res;
    }
private:
    void helper(vector<string>& res, string s, int n, int m){
        if(n==0 && m==0) { res.push_back(s); return; }

        if(n>0) helper(res, s+'(', n-1, m+1);
        if(m>0) helper(res, s+')', n, m-1);
    }
};

算法分析

解法一:

解法一其实是利用回溯递归来解决问题的。一看就都懂,但是就是不太好想。利用了n与m来记录正括号与反括号的数量。n > 0时,当添加了一个正括号,n就减少,但是相应的m加一;m>0,可以添加一个反括号,m减少,但是n不变。当n与m都为0的时候,说明正括号与反括号都添加完毕。

程序分析

略。

猜你喜欢

转载自blog.csdn.net/zy2317878/article/details/80889302