[LeetCode]Generate Parentheses

来源:互联网 发布:windows重置此电脑失败 编辑:程序博客网 时间:2024/06/08 15:58

题目

Number: 22
Difficulty: Medium
Tags: Backtracking, String

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:

"((()))", "(()())", "(())()", "()(())", "()()()"

题解

求括号的正确格式。

输入:整数n
输出:正确格式

用迭代的方法很好解决。

代码

vector<string> generateParenthesis(int n) {    vector<string> result;    if(0 == n)        return result;    addParenthese(result, "", n, 0);    return result;}void addParenthese(vector<string> &v, string str, int m, int n){    if(m == 0 && n == 0)    {        v.push_back(str);        return;    }    if(m > 0)        addParenthese(v, str + "(", m - 1, n + 1);    if(n > 0)        addParenthese(v, str + ")", m, n - 1);}
0 0