当前位置: 代码迷 >> 综合 >> leetcode_21 Generate Parentheses
  详细解决方案

leetcode_21 Generate Parentheses

热度:26   发布时间:2024-01-29 16:23:50.0

生成括号

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:

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

方法解析:跟上道题目一样,使用的是回溯法

终止条件:括号数量 等于 2*n

递归参数:当open左括号小于n,追加左括号,左括号数量+1

                  当close右括号小于open,追加右括号,右括号数量+1;

class Solution {
public:vector<string> res;void backtrace(string s,int open,int close,int max){if(s.length() == max*2)   {res.push_back(s);    return;}if(open < max){backtrace(s+"(",open+1,close,max);    }if(close < open){backtrace(s+")",open,close+1,max);    }}vector<string> generateParenthesis(int n) {if(n ==0)    return res;backtrace("",0,0,n);return res;}
};