Explore decision trees with pruning for subsets, permutations, and constraint satisfaction
# Math & Bits Templates
def gcd(a,b):
while b: a,b = b, a%b
return a
def lcm(a,b): return a//gcd(a,b)*b
def powmod(a,n,mod):
res=1; a%=mod
while n:
if n&1: res = (res*a)%mod
a=(a*a)%mod; n//=2
return resChoose/skip each element
def subsets(nums):
res=[]
def dfs(i, path):
if i==len(nums): res.append(path[:]); return
dfs(i+1, path)
path.append(nums[i]); dfs(i+1, path); path.pop()
dfs(0, [])
return resSwap/visited to permute
def permutations(nums):
res=[]; used=[False]*len(nums)
def dfs(path):
if len(path)==len(nums): res.append(path[:]); return
for i,x in enumerate(nums):
if used[i]: continue
used[i]=True; path.append(x); dfs(path); path.pop(); used[i]=False
dfs([]); return resPlace with constraints
def solve_n_queens(n):
cols=set(); d1=set(); d2=set(); res=[]; board=[['.']*n for _ in range(n)]
def dfs(r):
if r==n: res.append([''.join(row) for row in board]); return
for c in range(n):
if c in cols or (r-c) in d1 or (r+c) in d2: continue
cols.add(c); d1.add(r-c); d2.add(r+c); board[r][c]='Q'
dfs(r+1)
board[r][c]='.'; cols.remove(c); d1.remove(r-c); d2.remove(r+c)
dfs(0); return resExponential in depth.
Recursion depth.