第二周LeetCode算法题

题目名称: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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值