日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

回溯法解决01背包问题

發布時間:2024/9/15 编程问答 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 回溯法解决01背包问题 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

回溯法

問題的關鍵在于如何定義問題的解空間,轉化成樹(即解空間樹)。
只要是解可以描述成向量方式的,就可以使用回溯法,不斷的擴張部分向量,向下深入的過程就是,從部分解到可行解的過程。
解必須滿足多米諾性質:
可行解滿足約束–>部分解滿足約束
逆否為:部分解不滿足約束–>可行解不滿足約束

這樣可以用來pruning。

最簡單的回溯,解空間為二叉樹,又叫子集樹

遞歸方式實現的框架如下:

void backtrack(int t){ if(t > n) output(x); else{ for(int i = f(n,t); i <= g(n,t);i++){ x[t] = h(i); if(constraint(t) && bound(t)) backtrack(t+1); } } }

實現代碼如下:

def pack_01_back(N,V,C,W):BestResult = [0]*Nx = [0]*NBestValue = [0]CurCost = [0]CurValue = [0]def pack_01_back_tracking(depth):# 遞歸出口if depth > N-1:if CurValue[0] > BestValue[0]:BestValue[0] = CurValue[0]# x為可行解,在葉子處把可行解記錄下來BestResult[:] = x[:]print BestResultprint BestValue# 注意else的含義else:for i in range(2):x[depth] = iif i == 0:pack_01_back_tracking(depth+1)else:if CurCost[0] + C[depth] <= V:CurCost[0] += C[depth]CurValue[0] += W[depth]pack_01_back_tracking(depth+1)# 回溯時的處理,就是往上回溯時,要把吃進去的吐出來CurCost[0] -= C[depth]CurValue[0] -= W[depth]pack_01_back_tracking(0)return BestResult,BestValue

迭代方式實現

順序執行流程圖如下

代碼如下

注意不剪枝,回溯是在最底部,回溯到最后放入的那個物品

#%% def pack_01_back_iteration2(N,V,C,W):depth = 0 BestResult = [False]*NSelected = [False]*(N)BestValue = 0CurCost = 0CurValue = 0 while True:if depth < N:if CurCost + C[depth] <= V:Selected[depth] = TrueCurCost += C[depth]CurValue += W[depth]# 回溯是處于底部 else:if CurValue > BestValue:BestValue = CurValue BestResult[:] = Selected[:]# 到底部時,已經超了一個depth -=1while depth >= 0 and not Selected[depth]:depth -=1# 回溯到root退出if depth < 0:break# undoelse:Selected[depth] =FalseCurCost -= C[depth]CurValue -= W[depth]depth +=1return BestResult,BestValue#%% def pack_01_back_iteration(N,V,C,W):depth = 0BestResult = [False]*NSelected = [False]*(N)BestValue = 0CurCost = 0CurValue = 0while depth >= 0:while depth < N: if CurCost + C[depth] <= V:Selected[depth] = TrueCurCost += C[depth]CurValue += W[depth]depth +=1else:Selected[depth] = Falsedepth +=1if CurValue > BestValue:BestValue = CurValue BestResult[:] = Selected[:N]depth -=1while depth > 0 and Selected[depth] == 0:depth -=1if Selected[depth] ==1:Selected[depth] =FalseCurCost -= C[depth]CurValue -= W[depth]depth +=1if depth == 0:breakreturn BestResult,BestValue

運行結果:

#%% N = 8 V = 30 C = [11,2,3,9,13,6,15,7,19] W = [5,2,5,7,5,11,6,14]print pack_01_back(N,V,C,W) print pack_01_back_iteration(N,V,C,W) print pack_01_back_iteration2(N,V,C,W)runfile('/root/test/back_tracking.py', wdir='/root/test') ([False, True, True, True, False, True, False, True], [39]) ([False, True, True, True, False, True, False, True], 39) ([False, True, True, True, False, True, False, True], 39)

總結

以上是生活随笔為你收集整理的回溯法解决01背包问题的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。