Skip to content

Commit 7b55bdb

Browse files
committed
package 0 or 1
1 parent cc6bf38 commit 7b55bdb

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package backtracking;
2+
3+
public class Package0to1 {
4+
public int maxW = Integer.MIN_VALUE; //存储背包中物品总重量的最大值
5+
6+
public static void main(String[] args) {
7+
Package0to1 obj = new Package0to1();
8+
obj.maxW = Integer.MIN_VALUE;
9+
int[] items = {1, 10, 12, 20, 5, 6, 8, 2, 15, 16, 18};
10+
obj.f(0, 0, items, 10, 100);
11+
System.out.println("max weight is " + obj.maxW);
12+
}
13+
14+
// cw表示当前已经装进去的物品的重量和;i表示考察到哪个物品了;
15+
// w背包重量;items表示每个物品的重量;n表示物品个数
16+
// 假设背包可承受重量100,物品个数10,物品重量存储在数组a中,那可以这样调用函数:
17+
// f(0, 0, a, 10, 100)
18+
public void f(int i, int cw, int[] items, int n, int w) {
19+
if (cw == w || i == n) { // cw==w表示装满了;i==n表示已经考察完所有的物品
20+
if (cw > maxW) maxW = cw;
21+
return;
22+
}
23+
f(i+1, cw, items, n, w);
24+
if (cw + items[i] <= w) {// 已经超过可以背包承受的重量的时候,就不要再装了
25+
f(i+1,cw + items[i], items, n, w);
26+
}
27+
}
28+
29+
30+
}

0 commit comments

Comments
 (0)