Leetcode 22. Generate Parentheses
https://leetcode.com/problems/generate-parentheses/
#include<string>
using namespace std;
class Solution {
public:
vector<int> sta;
vector<string> ans;
void gene_next(int n,string s,int sta){
if(n==0){
ans.push_back(s+string(sta,')'));
return;
}
if(sta==0){
gene_next(n-1,s+'(',1);
return;
}
gene_next(n-1,s+'(',sta+1);
gene_next(n,s+')',sta-1);
return;
}
vector<string> generateParenthesis(int n) {
ans.clear();
if(n==0) return ans;
string s="";
int sta=0;
gene_next(n,s,sta);
return ans;
}
};
python版本
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
def next_letter(num,diff,tmp):
if diff==0 and num==0:
ans.append(''.join(tmp))
if diff>0:
tmp.append(')')
next_letter(num,diff-1,tmp)
tmp.pop()
if num>0:
tmp.append('(')
next_letter(num-1,diff+1,tmp)
tmp.pop()
return
ans=[]
next_letter(n,0,[])
return ans