leetcode题目例题解析(五)

leetcode题目例题解析(五)

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:
[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]

题意解析:

这道题并不复杂,只要通过排列组合的形式,括号匹配,保证每一个右括号都有一个相应的左括号

解题思路:

通过递归,每一层添加一个左括号或者右括号,并判断是否可以添加,最后的判断条件是左括号和右括号的数量都为n

代码:

class Solution {
public:
/*这里now是当前完成的字符串,每层都传到下层的都一样,所以不用引用传递*/
void find(vector<string>& ans, int a, int b, int n, string now) {
  if (a < n && b < n) {
    now = now + '(';
    string temp = now;
    find(ans, a + 1, b, n, now);  //连续添加左括号
    for (int j = b + 1; j <= a + 1; j++) {
      temp = temp + ')';
      find(ans, a + 1, j, n, temp);
    }
  } else if (a == n&&b == n) {
    ans.push_back(now);
  }
}
vector<string> generateParenthesis(int n) {
  vector<string> ans;
  string now = "";
  find(ans, 0, 0, n, now);
  return ans;
}
};

原题目链接:
https://leetcode.com/problems/generate-parentheses/description/

猜你喜欢

转载自blog.csdn.net/OzhangsenO/article/details/78239433