22:括号生成
括号是一对,所以每一次递归结束条件是字符串长度=2*n
有效括号判断:'('个数==')'个数时,当前必须是'(','('个数==n时,必须是')',其他情况当前位置遍历两边,既可以是'('又可以是')'
1 class Solution: 2 def generateParenthesis(self, n: int) -> List[str]: 3 if not n : return [] 4 re=[] 5 6 self.backtracking(2*n,re,"",0) 7 return re 8 def backtracking(self,n,re,path,index): 9 if(len(path)==n): 10 re.append(path) 11 return 12 for i in range(index,n): 13 num=self.isValid(path,i,n) 14 if(num): self.backtracking(n,re,path+num,i+1) 15 else: 16 self.backtracking(n,re,path+'(',i+1) 17 self.backtracking(n,re,path+')',i+1) 18 19 def isValid(self,path,index,n): 20 count1,count2=path.count('('),path.count(')') 21 if(count1==count2 ): return '(' 22 if(count1==n//2): return ')' 23 return 0generateParenthesis
89:格雷编码
天哪噜,谁敢信这么个玩意做了一下午
标签:return,第八天,self,re,num,path,Leetcode,backtracking,刷题 From: https://www.cnblogs.com/xiaoruru/p/18003636