代码如下:
package suanfa6;
import java.io.File;
import java.io.FileOutputStream;
public class Attribute {
static public int MaxSize=20; //设置容量
static public int Weight[]={4,12,1,2,1}; //物品的重量
static public int Value[]={10,4,2,2,1}; //物品的价值
static public int Result[]={-1,-1,-1,-1,-1};//初始化背包
public class Bag {
public static void main(String[] args) {
Bag bag=new Bag();
System.out.println(bag.get(4,15));
bag.print();
bag.writeIntoFile(Attribute.Result);
}
public void print(){
for(int i=0;i<Attribute.Result.length;i++)
{
System.out.println(Attribute.Result[i]);
}
}
//递归方式求解
public int get(int n ,int count)
{
if(n==-1||count==0)
return 0;
int tmp1=get(n-1,count);
if(Attribute.Weight[n]>count)
{
Attribute.Result[n]=0;
return tmp1;
}
int tmp2=Attribute.Value[n]+get(n-1,count-Attribute.Weight[n]);
if(tmp1>tmp2)
{
Attribute.Result[n]=0;
return tmp1;
}
Attribute.Result[n]=1;
return tmp2;
}
//写入txt
public void writeIntoFile(int[] list) {
File f = new File("src/KnapsackResult.txt");
FileOutputStream fou = null;
try {
fou = new FileOutputStream(f, true);
for (int i = 0; i < list.length; i++) {
String s = String.valueOf(list[i]);
String a = "" + s + "\t\n";
// byte []bytes=new byte[1024];
// 如何把string转换byte数组
fou.write(a.getBytes());
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
try {
fou.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}