Java实现-背包问题VI

给出一个都是正整数的数组 nums,其中没有重复的数。从中找出所有的和为 target 的组合个数。

 注意事项

一个数可以在组合中出现多次。
数的顺序不同则会被认为是不同的组合。

样例

给出 nums = [1, 2, 4], target = 4
可能的所有组合有:

[1, 1, 1, 1]
[1, 1, 2]
[1, 2, 1]
[2, 1, 1]
[2, 2]
[4]

返回 6

public class Solution {
    /**
     * @param nums an integer array and all positive numbers, no duplicates
     * @param target an integer
     * @return an integer
     */
    public int backPackVI(int[] nums, int target) {
        // Write your code here
        int[] dp=new int[target+1];
		dp[0]=1;
		for(int i=1;i<=target;i++){
			for(int j=0;j<nums.length;j++){
				if(nums[j]<=i){
					dp[i]+=dp[i-nums[j]];
				}
			}
		}
		return dp[target];
    }
    
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
Java中贪心算法解决背包问题的代码如下所示: ```java import java.util.*; class ItemValue { double cost; double wt, val, ind; public ItemValue(double wt, double val, double ind) { this.wt = wt; this.val = val; this.ind = ind; cost = val / wt; } } class Knapsack { static double maxValue(int[] wt, int[] val, int capacity) { ItemValue[] iVal = new ItemValue[wt.length]; for (int i = 0; i < wt.length; i++) { iVal[i] = new ItemValue(wt[i], val[i], i); } Arrays.sort(iVal, new Comparator<ItemValue>() { @Override public int compare(ItemValue o1, ItemValue o2) { return Double.compare(o2.cost, o1.cost); } }); double totalValue = 0d; for (ItemValue i : iVal) { double curWt = (double) i.wt; double curVal = (double) i.val; if (capacity - curWt >= 0) { capacity -= curWt; totalValue += curVal; } else { double fraction = capacity / curWt; totalValue += (curVal * fraction); capacity -= (curWt * fraction); break; } } return totalValue; } } public class Main { public static void main(String[] args) { int[] wt = { 10, 40, 20, 30 }; int[] val = { 60, 40, 100, 120 }; int capacity = 50; double maxValue = Knapsack.maxValue(wt, val, capacity); System.out.println("Maximum value we can obtain = " + maxValue); } } ``` 该代码实现一个背包问题的贪心算法。其中,背包问题的定义是:给定n个物品和一个容量为W的背包。物品i的重量是wi,价值是vi。求装入背包的物品的最大价值。 代码使用了自定义的ItemValue类,存储每个物品的价值、重量、索引以及性价比。然后将所有物品按照性价比从大到小排序,然后依次加入背包中,直到背包装满或者物品已经全部加入为止。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Narasimha_Karumanchi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值