题目:
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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]题意:
这道题注意一个生成括号很明显的特征,那就是在放置括号的时候,如果剩余的左括号数大于等于剩余的右括号数,这时候一定要放置左括号,不能放置右括号。
一种递归实现的算法如下:
输入:vector<string> result, string s = "", int n, int leftnums = n, int rightnums = n;
输出:vector<string> result
function solution() {
若leftnums = 0 并且 rightnums = 0, 将s加入result中
若leftnums > 0 则递归调用( s += ‘(’, leftnums -1 )
若rightnums > 0 则递归调用( s += ‘)’, rightnums -1)
}
一种c++的代码实现如下:
#include<iostream>
#include<vector>
#include<string>
using namespace std;
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> result;
string s = "";
int left_bracket_nums = n;
int right_bracket_nums = n;
recursion_Parenthesis(result,s,left_bracket_nums,right_bracket_nums);
return result;
}
void recursion_Parenthesis(vector<string> &result, string s, int left_bracket_nums, int right_bracket_nums) {
if(left_bracket_nums == 0 && right_bracket_nums == 0) {
result.push_back(s);
}
if(left_bracket_nums > 0) {
recursion_Parenthesis(result,s+'(',left_bracket_nums-1,right_bracket_nums);
}
if(right_bracket_nums > 0 && left_bracket_nums < right_bracket_nums) {
recursion_Parenthesis(result,s+')',left_bracket_nums,right_bracket_nums-1);
}
}
};