来源:力扣(LeetCode)
链接: https://leetcode.cn/problems/generate-parentheses/
数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
示例 1:
输入:n = 3
输出:["((()))","(()())","(())()","()(())","()()()"]
示例 2:
输入:n = 1
输出:["()"]
提示:
python实现
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
ans = []
# 先生成所有可能的组合,并对每种组合进行判断是否符合标准
def helper(ss=[]):
if len(ss) == 2*n:
if self.valid(''.join(ss)):
ans.append(''.join(ss))
else:
ss.append('(')
helper(ss)
ss.pop()
ss.append(')')
helper(ss)
ss.pop()
helper()
return ans
def valid(self, s):
counts = 0
for char in s:
if char == '(':
counts += 1
else:
counts -= 1
if counts < 0:
return False
return counts == 0
c++实现
class Solution {
private:
vector<string> ans;
public:
bool valid(string s) {
int counts = 0;
for(char ch: s) {
if (ch == '(')
counts++;
else
counts--;
if (counts < 0)
return false;
}
return counts == 0;
}
string convert(vector<char> cs, int size) {
string s;
for(int i=0; i<size; i++)
s += cs[i];
return s;
}
void _generateParenthesis(vector<char> cs, int n) {
if (cs.size() == 2 * n) {
string s = convert(cs, 2*n);
if (valid(s))
ans.push_back(s);
}
else {
cs.push_back('(');
_generateParenthesis(cs, n);
cs.pop_back();
cs.push_back(')');
_generateParenthesis(cs, n);
cs.pop_back();
}
}
vector<string> generateParenthesis(int n) {
_generateParenthesis({}, n);
return ans;
}
};
复杂度分析
python实现
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
ans = []
def helper(l, r, s):
# 递归结束条件
if len(s) == 2*n:
ans.append(s)
if len(s) > 2 * n:
return
# 开始处理
if l < n:
helper(l+1, r, s+'(')
if r < l and r < n:
helper(l, r+1, s+')')
helper(0, 0, '')
return ans
c++实现
class Solution {
private:
vector<string> ans;
public:
int _generateParenthesis(int left, int right, int n, string s) {
if (s.size() == 2 * n)
ans.push_back(s);
if (s.size() > 2*n)
return -1;
if (left < n)
_generateParenthesis(left+1, right, n, s+'(');
if (right < left)
_generateParenthesis(left, right+1, n, s+')');
return 0;
}
vector<string> generateParenthesis(int n) {
_generateParenthesis(0, 0, n, "");
return ans;
}
};
复杂度分析
python实现
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
if n == 1:
return ['()']
res = set()
for i in self.generateParenthesis(n-1):
for j in range(len(i)+2):
res.add(i[0:j] + '()' + i[j:])
return list(res)
c++实现
class Solution {
public:
vector<string> generateParenthesis(int n) {
if (n==1)
return {"()"};
unordered_map<string, int> mp;
vector<string> res;
string tmp;
for (auto& s: generateParenthesis(n-1)) {
for (int i=0; i < 2*(n-1); i++) {
tmp = s.substr(0, i) + "()" + s.substr(i, 2*(n-1));
if (mp[tmp] == 0) {
++mp[tmp];
res.push_back(tmp);
}
}
}
return res;
}
};
复杂度分析