解答:
方法一:dfs
class Solution
{
public:
vector<string>retArr;
vector<string> generateParenthesis(int n)
{
if(n==0)
return retArr;
dfs("",0,0,n);
return retArr;
}
private:
void dfs(string str,int left,int right,int n)
{
if(left==n&&right==n)
{
retArr.push_back(str);
return;
}
if(right>left) //右括号的个数大于左括号的数字
return;
if(left<n)
dfs(str+"(",left+1,right,n);
if(right<n)
dfs(str+")",left,right+1,n);
}
};
方法二:动态规划