单一背包问题

题目
  • 求背包能装下的物品组合
  • 例如:给定物品重量,int[] arr = {1, 2, 3, 4, 5},背包能容纳的总重量为12,输出[1 2 3 4 ] 和 [3 4 5]
解法
    /**
     * 单一背包问题
     *
     * @param arr
     * @param total
     */
    public static void knapsackQuestion(int[] arr, int total) {
        if (arr == null || arr.length < 0 || total < 0) return;
        boolean[] selected = new boolean[arr.length];
        knapsack(arr, selected, total, 0);
    }

    /**
     * 找出符合承重重量的组合
     *
     * @param total 总重量
     * @param index 可供选择的重量下标
     */
    public static void knapsack(int[] arr, boolean[] selects, int total, int index) {
        if (total < 0 || total > 0 && index >= arr.length) {
            return; // 没找到解决办法,直接返回
        }
        // 总重量为0,则找到解决办法了
        if (total == 0) {
            for (int i = 0; i < index; i++) {
                if (selects[i]) {
                    System.out.print(arr[i] + " ");
                }
            }
            System.out.println();
            return;
        }
        // 第一个合适
        selects[index] = true;
        knapsack(arr, selects, total - arr[index], index + 1);
        
        // 沒有找到合适数据,重置,从第二个开始查找
        selects[index] = false;
        knapsack(arr, selects, total, index + 1);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值