算法课第7周作业——背包问题

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();    
            }    
        }    
    }    
}  




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值