Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
LeetCode/generate-parentheses
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
43 lines (39 sloc)
1.06 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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: | |
[ | |
"((()))", | |
"(()())", | |
"(())()", | |
"()(())", | |
"()()()" | |
] | |
My code: | |
class Solution: | |
def generateParenthesis(self, n): | |
""" | |
:type n: int | |
:rtype: List[str] | |
""" | |
result=[] | |
result=self.generateset(result,n) | |
return result | |
def generateset(self,result,n): | |
if n==0: | |
return | |
if n==1: | |
result.append('()') | |
return result | |
result=self.generateset(result,n-1) | |
#print('executing %d'%n) | |
new_result=[] | |
for i in range(len(result)): | |
item=result[i] | |
for j in range(len(item)): | |
tmp_item=item[0:j]+'()'+item[j:] | |
#print(tmp_item) | |
if tmp_item not in new_result: | |
new_result.append(tmp_item) | |
result=new_result | |
return result | |
Solution: | |
https://leetcode.com/problems/generate-parentheses/ |