用回溯法解决0-1背包问题
2015-05-31 15:52
441 查看
以下是没有剪枝的算法:
public class Knapsack { static double C;//背包容量 static double[] P;//物品价值 static double[] W;//物品重量 static int N;//物品个数 static double bestP; static double currP; static double currW; public static void main(String[] args) { N=4;C=7; P=new double[]{9.0,10.0,7.0,4.0}; W=new double[]{3.0,5.0,2.0,1.0}; double result=test(); System.out.println("the best result is"+result); } public static double test(){ backTrace(0); return bestP; } public static void backTrace(int t){ if(t==N){ System.out.println("this branch CurrentValue:"+currP+"CurrentWeight:"+currW); if(currW>C)return; if(currP>bestP)bestP=currP; return; } else { currW+=W[t]; currP+=P[t]; backTrace(t+1); currW-=W[t]; currP-=P[t]; backTrace(t+1); } } }
相关文章推荐
- Source Insight上添加svn命令,打开当前文件夹命令
- 第三章 生产要素市场
- iOS核心面试题 ~
- Java笔记--泛型
- Python之学习笔记(正则表达式)
- solr分页查询和高亮
- mark:如何使用FileZilla连接虚拟机上的Fedora
- JSP 基于Oracle分页
- iptables对报文中TTL的操作
- Merge Sort的java语言实现
- 执行 maven 命令 报错Unable to add module to the current project as it is not of packaging type 'pom'[转]
- TalkingData美国旧金山之行 —— Twitter
- Internal Sorting: Straight selection sort: Sorting by Selection
- ListView的优化
- Python之学习笔记(模块的使用)
- Struts2中获取请求参数
- Unity中用触摸控制物体旋转和放大
- A*算法完全理解
- java final域
- I/O模型与Nginx配置