背包算法(一)

一个旅行者有一个最多能装W千克的包,先有n种物品,每种物品的重量是W1,W2....Wn。求旅行者可装入最重物品的组合及组合数量!

分析:这是一道数学求组合的问题,也是最简单的背包算法,找出所有满足总重量的组合即可。

下面是我用java做出的解法

package com.test;

import java.util.ArrayList;
import java.util.List;

/**
 * 简单背包算法
 * 
 * @author taojinsha
 *
 */
public class TestBag {

	private int[] bags;
	private int totalWeight;
	private List<Object> result;

	private List<Object> getBgsArrays(int[] bags, int totalWeight) {
		this.bags = bags;
		this.totalWeight = totalWeight;
		result = new ArrayList<Object>();
		initBags(0);
		return result;
	}

	private void initBags(int depth) {
		if (depth < bags.length - 1) {
			getBags(depth + 1);
		} else {
			System.out.println("共有:" + result.size() + "种结果");
			for (int i = 0; i < result.size(); i++) {
				System.out.println(result.get(i));
			}
		}
	}

	/**
	 * 根据组合个数递归找到所有组合
	 * @param depth
	 */
	private void getBags(int depth) {
		getCombinationsByLength(depth);
		initBags(depth);
	}

	/**
	 * 求当前组合内的物品总重量
	 * @param v
	 * @return
	 */
	private int getTotal(List<Integer> v) {
		int total = 0;
		for (int i = 0; i < v.size(); i++) {
			total += v.get(i);
		}
		return total;
	}

	public void getCombinationsByLength(int length) {
		List<Integer> newData = new ArrayList<Integer>();
		for (int i : bags) {
			newData.add(i);
		}
		List<Integer> initialCombination = new ArrayList<Integer>();
		combination(newData, initialCombination, length);
	}

	/**
	 * 利用递归算法求组合
	 * @param data
	 * @param initialCombination
	 * @param length
	 */
	private void combination(List<Integer> data,
			List<Integer> initialCombination, int length) {
		if (length == 1) {
			for (int i = 0; i < data.size(); i++) {
				List<Integer> newCombination = cloneList(initialCombination);
				newCombination.add(data.get(i));
				if (getTotal(newCombination) == totalWeight) {//当组合总重量满足背包最大重量时
					result.add(newCombination);
				}

			}
		}

		if (length > 1) {
			for (int i = 0; i < data.size(); i++) {
				List<Integer> newCombination = cloneList(initialCombination);
				newCombination.add(data.get(i));

				List<Integer> newData = cloneList(data);
				for (int j = 0; j <= i; j++) {
					if (j < data.size()) {
						newData.remove(data.get(j));
					}
				}
				combination(newData, newCombination, length - 1);
			}
		}
	}

	private List<Integer> cloneList(List<Integer> data) {
		List<Integer> newData = new ArrayList<Integer>();
		for (Integer str : data) {
			newData.add(str);
		}
		return newData;
	}

	public static void main(String args[]) {
		int[] bags = { 15, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 13 };
		int totalWeight = 20;
		TestBag tb = new TestBag();
		tb.getBgsArrays(bags, totalWeight);
	}

}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值