0-1背包问题java代码
时间: 2023-10-14 13:29:49 浏览: 81
0-1背包问题 C和java两种实现
5星 · 资源好评率100%
以下是一个简单的0-1背包问题的Java代码:
```
public class KnapsackProblem {
public static int knapsack(int[] weights, int[] values, int capacity) {
int n = weights.length;
int[][] dp = new int[n + 1][capacity + 1];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= capacity; j++) {
if (weights[i - 1] <= j) {
dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - weights[i - 1]] + values[i - 1]);
} else {
dp[i][j] = dp[i - 1][j];
}
}
}
return dp[n][capacity];
}
public static void main(String[] args) {
int[] weights = {10, 20, 30};
int[] values = {60, 100, 120};
int capacity = 50;
System.out.println(knapsack(weights, values, capacity));
}
}
```
该代码使用动态规划的思想解决了0-1背包问题,时间复杂度为O(N*W),其中N是物品数量,W是背包容量。
阅读全文