背包问题

问题:

给定n种物品,物品i的重量是wi,价值为vi,背包的重量为c,请问怎么放,背包里的物品价值最大。

分析:

对于n种物品的每一种的选择只有放或不放两种选择。

例如 n=3 可构造下面的二叉树

代码1:


public class L2 {
 static int n = 3;//物品数
 static int thing[][] = {{10,5},{4,4},{5,1}};//重量和价值
 static int c = 16;//最大承重
 static int rw = 0;//当前包的重量  
 public static void main(String[] args) {
  
  System.out.println(f(0,c));
  
  
 }
 private static int f(int m, int rw) {
  if(m==n){//如果搜索到最后返回0
   return 0;
  }
  
  if(rw<thing[m][0]){//判断当前物品是否还可以放入背包
   return f(m+1,rw);//不可以
  }
  else{//可以
   //有选择放还是不放

  //放的话将价值加上
   return Math.max(f(m+1,rw), f(m+1,rw-thing[m][0])+thing[m][1]);
  }
 }

}

这只是一种方法,当n过大的时候由于使用递归和有可能计算重复的数据使得效率低。

以后会有另外的算法。

 

 

ps:过几天和大家一起学习5大常用算法 哦啦啦啦。。。。。。。

 

posted @ 2017-04-11 19:05  Aaronn  阅读(196)  评论(0编辑  收藏  举报