classSolution:defbacktrace(self,path,inum):iflen(path)== self.k:
self.ans.append(path[:])return## 完全回溯# for i in range(inum,self.n+1):## 剪枝for i inrange(inum,self.n-(self.k-N)+1+1):
self.backtrace(path+[i],i+1)defcombine(self, n:int, k:int)-> List[List[int]]:
self.ans =[]
self.k = k
self.n = n
self.backtrace([],1)return self.ans
classSolution:defisTrue(self,s):
left,right =0,len(s)-1while(left<right):if s[left]!=s[right]:returnFalse
left +=1
right -=1returnTruedefbacktrace(self,path,s,ans):ifnot s:
ans.append(path)for i inrange(1,len(s)+1):
temp = s[:i]if self.isTrue(temp)isFalse:continue
self.backtrace(path+[temp],s[i:],ans)defpartition(self, s:str)-> List[List[str]]:
ans =[]
self.backtrace([],s,ans)return ans
classSolution:defrestoreIpAddresses(self, s:str)-> List[str]:defbacktrace(path,s,ans,k):ifnot s and k==4:
ans.append(path[:-1])if k>4:returnfor i inrange(1,len(s)+1):iflen(s[:i])>3or(len(s[:i])>1and s[:i][0]=='0')orint(s[:i])>255:break
backtrace(path+s[:i]+'.',s[i:],ans,k+1)
ans =[]
backtrace('',s,ans,0)return a