第二周LeetCode算法题

来源:互联网 发布:网络语言99是什么意思 编辑:程序博客网 时间:2024/05/16 04:56

题目名称:Generate Parentheses

题目难度:Medium

题目描述: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:

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

题目分析:
题目的意思就是找出所有合法的对应于输入数的括号匹配形式。最直接想到的就是穷举法。写出一个递归函数,他有4个参数,第一个是结果的引用,用于每出一个结果之后的实时记录;第二个是记录当前还剩多少个左括号可以加;第三个是记录当前还剩多少个右括号可以加;第四个是当前正在拼接的字符串。
递归函数开始先检查是否满足终止条件:即待添加的左右括号数是否为0。如果都没有待添加的,则是终止情况。如果还有待添加的,分别检查是否有待添加的左右括号。能添加左括号的条件是待添加的左括号数>0,能添加右括号数的条件是待添加的右括号数>0并且已添加的左括号数多于右括号数。

最后AC的代码如下:

class Solution {public:    void nextOne(vector<string> & result, int left, int right, string current) {  if (right == 0 && left == 0) {      result.push_back(current);      return;  }  if (left > 0) {    nextOne(result, left-1, right, current+"(");  }  if (right > left) {    nextOne(result, left, right-1, current+")");  }}    vector<string> generateParenthesis(int n) {      int left = n, right = n;      vector<string> result;      nextOne(result, left, right, "");      return result;    }};
原创粉丝点击