function [res, sel] = KnapSack(value, weight, n, W) res = zeros(n,W); lastsel = zeros(n,W); sel = zeros(n,W); for i=1:n for w=1:W if weight(i) <= w if i==1 [res(i,w) I] = max([0, value(i)]); if I==2 sel(:,w) = zeros(n,1); sel(i,w) = 1; end else if weight(i) == w [res(i,w) I] = max([res(i-1,w), value(i)]); if I==2 sel(:,w) = zeros(n,1); sel(i,w) = 1; end else [res(i,w) I] = max([res(i-1,w), value(i) + res(i-1,w-weight(i))]); if I==2 sel(:,w) = lastsel(:,w-weight(i)); sel(i,w) = 1; end end end else if i==1 res(i,w) = 0; else res(i,w) = res(i-1,w); end end end lastsel = sel; end
matlab怎么处理背包问题,0-1背包问题的Matlab算法
最新推荐文章于 2024-08-27 12:22:52 发布