mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 04:06:51 +08:00
update 背包理论基础01背包-2 java代码
This commit is contained in:
@ -211,9 +211,35 @@ int main() {
|
|||||||
|
|
||||||
## 其他语言版本
|
## 其他语言版本
|
||||||
|
|
||||||
|
|
||||||
Java:
|
Java:
|
||||||
|
|
||||||
|
```java
|
||||||
|
public static void main(String[] args) {
|
||||||
|
int[] weight = {1, 3, 4};
|
||||||
|
int[] value = {15, 20, 30};
|
||||||
|
int bagWight = 4;
|
||||||
|
testWeightBagProblem(weight, value, bagWight);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void testWeightBagProblem(int[] weight, int[] value, int bagWeight){
|
||||||
|
int wLen = weight.length;
|
||||||
|
//定义dp数组:dp[j]表示背包容量为j时,能获得的最大价值
|
||||||
|
int[] dp = new int[bagWeight + 1];
|
||||||
|
//遍历顺序:先遍历物品,再遍历背包容量
|
||||||
|
for (int i = 0; i < wLen; i++){
|
||||||
|
for (int j = bagWeight; j >= weight[i]; j--){
|
||||||
|
dp[j] = Math.max(dp[j], dp[j - weight[i]] + value[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
//打印dp数组
|
||||||
|
for (int j = 0; j <= bagWeight; j++){
|
||||||
|
System.out.print(dp[j] + " ");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
Python:
|
Python:
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user