回溯是一种枚举, 在枚举的过程中,通过条件判断是否成立,来进行剪枝,以此来降级时间复杂度,
eg1. 0-1背包 。
有n个物品,每个物品的重量分别是n1, n2...... 容器最大能装max的重量,问 怎么样装可以装的最重
思路:
每个物品都有两种选择, 装或者不装,当考察到最后一个物品的时候或者当前的重量已经超过max 则结束。采用递归的方式,
current_max = 0 # 用全局变量记录最大值
result = []
def solution(nums, max_weight):
def execute(i, current_weight, tmp_list):
if i == len(nums) or current_weight == max_weight: #返回的终止条件
if current_weight > current_max:
global current_max
current_max = current_weight
if current_weight == max_weight:
result.append(tmp_list)
return
execute(i+1, current_weight, tmp_list) #选择不装
if current_weight + nums[i] <= max_weight:
execute(i+1, current_weight + nums[i], tmp_list+[nums[i]]) 装入
execute(0, 0, [])
nums = [2, 5, 4, 8, 1]
max_weight = 10
solution(nums, max_weight)