回溯Leetcode
问题:输出的是全排列,多少种组合,
***当有重复出现 可用字典记录个数,用list记录是否使用过
一维问题的回溯秒杀:
216. 组合总和 III
def combinationSum3(self, k: int, n: int) -> List[List[int]]: out=[] def f(s,i,sum1): if len(s)==k: if sum1==n: out.append(s) return if sum1>n: return for j in range(i,10): f(s+[j],j+1,sum1+j) f([],1,0) return out
77. 组合
def combine(self, n: int, k: int) -> List[List[int]]: out=[] def f(i,s): if len(s) ==k: out.append(s) return #if len(s)>k: for j in range(i,n+1): f(j+1,s+[j]) f(1,[]) return out
1079. 活字印刷
def numTilePossibilities(self, tiles: str) -> int: dic={} n=[0] for i in range(len(tiles)): if tiles[i] not in dic: dic[tiles[i]] = 1 else: dic[tiles[i]] +=1 def f(d): for key in d: if d[key]>0: d1 =d.copy() d1[key]-=1 f(d1) n[0]+=1 f(dic) return n[0]