Last Updated: 2023-11-01 14:28:19 Wednesday
-- TOC --
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. n is [0,8].
Example 1:
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Example 2:
Input: n = 1
Output: ["()"]
输入的数字n表示有多少对括号,输入这n对括号所有合法的组合。n被限制在0到8,n不能太大,否则组合数会指数级的增长。
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
s = set()
s.add('()')
for i in range(n-1):
p = set()
for it in s:
for j in range(len(it)):
p.add(it[:j]+'()'+it[j:])
s = p
return list(s)
因为输入只有括号的两个符号,所以重复的情况很多,set能自动过滤重复组合,最后转list返回。
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
def _backtrack(comb, nlp, nrp):
if nlp == nrp == 0:
yield comb
return
if nlp:
yield from _backtrack(comb+'(', nlp-1, nrp)
if nrp > nlp:
yield from _backtrack(comb+')', nlp, nrp-1)
return list(_backtrack('',n,n))
class Solution {
vector<string> r;
void backtrack(string t, int left, int right){
if(left==0 && right==0){
r.push_back(t);
return;
}
if(left > 0)
backtrack(t+'(', left-1, right);
if(right > left)
backtrack(t+')', left, right-1);
return;
}
public:
vector<string> generateParenthesis(int n) {
r.clear();
backtrack("", n, n);
return r;
}
};
static char **r;
static int ridx;
static void _backtrack(const int size, char *it, int idx, int nlp, int nrp){
if(nlp==0 && nrp==0){
if(ridx%64 == 0)
r = realloc(r, sizeof(char*)*(ridx/64+1)*64);
r[ridx] = malloc(size);
memcpy(r[ridx], it, size);
++ridx;
return;
}
if(nlp > 0){
it[idx] = '(';
_backtrack(size, it, idx+1, nlp-1, nrp);
}
if(nrp > nlp){
it[idx] = ')';
_backtrack(size, it, idx+1, nlp, nrp-1);
}
return;
}
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
char ** generateParenthesis(int n, int* returnSize){
int size = n*2 + 1;
char *it = malloc(size);
it[size-1] = 0;
r = NULL;
ridx = 0;
_backtrack(size, it, 0, n, n);
*returnSize = ridx;
return r;
}
本文链接:https://cs.pynote.net/ag/leetcode/202310212/
-- EOF --
-- MORE --