---
title: "背包问题"
author: "wangyun"
date: "2008-05-29T16:50:10Z"
tags: []
slug: "untitled"
draft: false
lastmod: "2008-05-29T16:50:10Z"
id: 198361
url: "https://wangyun.iteye.com/blog/198361"
---

刚才看了一篇关于背包问题的解决之道，文章中使用了递归的方法对背包问题的求解。看完之后，我背包问题有所了解，背包问题是一种常见组合的问题：组合一定量的已知数据使其等于某个特定数的组合问题（如2，4，6，10数据，数据相加为14的组合）。

首先，我先将文章中提到某些“关键词”进行列举：
1）源数据：
2）背包：已选中的数据


接下来，介绍下背包的算法思路：
针对第n个数据，有两种情况1）选中第n个数据。2）不选中第n个数据
选中第n个数据：背包问题变成为对指定数据减去第n个数据的背包问题。
不选中第n个数据：背包问题成为剩下数据的背包问题。

代码如下：
/**
	 *  背包求解
	 *  @param array 数组
	 *  @param total 特定数
	 *  @param offset 当前数组位置
	 *  @param bag 背包数据
	 */
	public static List bag(int array, int total, int offset, int bag) {
		List list = new ArrayList();
		if(0 == total) {
			list.add(toString(bag));
			return list;
		}
		
		
		while(array.length > offset && total < array)
			offset++;
		if(array.length <= offset)
			return list;
		
		//不包含offset位置的数据
		//背包问题成为剩下数据的背包问题。
		list.addAll(bag(array, total, offset + 1, bag.clone()));
		
		//包含offset位置的数据
		//背包问题变成为对指定数据减去array数据的背包问题
		list.addAll(bag(array, total - array, offset + 1, put(bag, array)));
	
		return list;
	}
	
	/**
	 *  将n放入数组最后一个元素之后
	 *  @param array 数组
	 *  @param n 元素
	 *  @return 返回添加好元素的数组
	 */
	public static int put(int array, int n) {
		int i = -1;
		while(0 < array);
		array* = n;
		return array;
	}
	
	/**
	 *  数组转化为字符串
	 *  @param array 数组
	 *  @return 字符串
	 */
	public static String toString(int array) {
		StringBuffer buffer = new StringBuffer("").toString().replaceAll(", ]", "]");
	}