22.生成所有的括号组合

来源:互联网 发布:php while 死循环 编辑:程序博客网 时间:2024/06/08 07:13

Generate Parentheses

问题描述:

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:

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

知识补充:

引用的使用

void add_s(vector<string> &r,string str,int left ,int right)//其中vector<string> &r,我们需要使用引用&来保证参数的传递,如果不使用引用只是一个形参对r的操作无法影响到初始的r,使用引用后相当于是r的别名,对他的操作就相当于对r本身的操作

测试代码:

int main(){    int n = 4;    vector<string> result;    add_s(result,"",n,0);    return result;}void add_s(vector<string> &r,string str,int left ,int right){    if(left==0&&right==0)    {        r.push_back(str);        return;    }    if(left>0)    {        add_s(r,str+"(",left-1,right+1);    }    if(right>0)    {        add_s(r,str+")",left,right-1);    }}

这里写图片描述

原创粉丝点击