leetcode No22. Generate Parentheses

来源:互联网 发布:家用网络存储器 编辑:程序博客网 时间:2024/05/22 11:36

Question:

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:

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

Algorthim:

此题可以用二叉树的思想:
当左括号个数小于n时,添加左括号
当左括号个数大于右括号时,添加右括号
Ex:假设n=3,先添加左括号(右括号一样),如图所示:

Accepted Code:

class Solution {public:    vector<string> generateParenthesis(int n) {        vector<string> res;        helper(res,"",n,n);        return res;    }    void helper(vector<string> &res,string tmp,int left,int right)    {        if(left==0 && right==0)        {            res.push_back(tmp);            return;        }        if(left>0)            helper(res,tmp+'(',left-1,right);        if(left<right)  //此时左括号的个数大于右括号            helper(res,tmp+')',left,right-1);    }};


0 0
原创粉丝点击