dfs的本质是暴力枚举
dfs模板
我觉得dfs最主要的是最后递归条件的实现
例题1:
答案:
给定一个数字x,将其拆分为n个正整数,后一个要求大于等于前一个,给方案
n = int(input())
x = int(input())
path = [0] * n
def dfs(depth):
#depth:表示当前处于第depth层
#递归出口
if depth == n:
#判断数字是否递增
for i in range(1,n):
if path[i] >= path[i-1]:
continue
else:
return
if sum(path) != x:
return
#答案
print(path)
return
#对于每一层,枚举当前拆出的数字
for i in range(1,x+1):
path[depth] = i
dfs(depth + 1)
dfs(0)
优化后答案:
#剪枝
n = int(input()) #层数
x = int(input()) #总和
path = [0] * n
def dfs(depth,last_valie):
if depth == n:
if sum(path) == x:
print(path)
return
for i in range(last_valie,x+1):
path[depth] = i
dfs(depth+1,i)
dfs(0,1)
思路:
放入了一个新的参数last_valie,用来实现数字递增,降低时间复杂度
例题2:分糖果
答案:
ans = 0
def dfs(depth,n,m):
#depth:第几个小朋友
#n:第一类糖果的数量
#m:第二类糖果的数量
if depth == 7:
if n == 0 and m == 0:
global ans
ans += 1
return
#每个小朋友的情况
#枚举第一种糖果
for i in range(0,6):
#枚举第二种糖果
for j in range(0,6):
if 2 <= i + j <= 5 and i <= n and j <= n:
dfs(depth + 1 , n - i , m -j)
dfs(0,9,16)
print(ans)