01背包问题动态规划Java
时间: 2023-11-10 15:05:02 浏览: 87
背包问题 动态规划 java
5星 · 资源好评率100%
好的,以下是01背包问题动态规划Java的代码:
```java
public class Knapsack {
public static int knapsack(int[] w, int[] v, int C) {
int n = w.length;
int[][] memo = new int[n][C + 1];
for (int j = 0; j <= C; j++) {
memo[0][j] = (j >= w[0] ? v[0] : 0);
}
for (int i = 1; i < n; i++) {
for (int j = 0; j <= C; j++) {
memo[i][j] = memo[i - 1][j];
if (j >= w[i]) {
memo[i][j] = Math.max(memo[i][j], v[i] + memo[i - 1][j - w[i]]);
}
}
}
return memo[n - 1][C];
}
public static void main(String[] args) {
int[] w = {1, 2, 3};
int[] v = {6, 10, 12};
int C = 5;
System.out.println(knapsack(w, v, C));
}
}
```
阅读全文