作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有java中背包问题的递归解决方案,这是我的代码:
public class OptimalIncome{
final static int length[] = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
final static int price[] = new int[] {1, 5, 8, 9, 10, 17, 17, 20, 24, 30};
public static int totalLength = 9;
public static int bestCut(int i, int totalLength){
if(i < 0){
return 0;
}
else if(length[i] > totalLength){
return bestCut(i - 1, totalLength);
}
else{
return Math.max(bestCut(i - 1, totalLength), bestCut(i - 1, totalLength - length[i]) + price[i]);
}
}
public static void main(String[] args){
System.out.println("Given total rod length : " + totalLength);
System.out.println("Maximum income : " + bestCut(price.length-1, totalLength));
System.out.println("Smaller part sets : ");
}
}
它工作得很好,正如你所看到的,我想打印一组选择(较小的部分)。我怎样才能做到这一点?谢谢
最佳答案
我们开始:
导入java.util.ArrayList;导入java.util.List;
public class OptimalIncome {
final static int length[] = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
final static int price[] = new int[] { 1, 5, 8, 9, 10, 17, 17, 20, 24, 30 };
public static int totalLength = 9;
static List<Integer> pickedObjects = new ArrayList<Integer>();
public static int bestCut(int i, int totalLength) {
if (i < 0) {
return 0;
} else if (length[i] > totalLength) {
return bestCut(i - 1, totalLength);
} else {
return Math.max(bestCut(i - 1, totalLength),
bestCut(i - 1, totalLength - length[i]) + price[i]);
}
}
public static void printSolution(int i,int totalLength){
if(i < 0)
return;
else if(length[i]>totalLength){
printSolution(i-1, totalLength);
}else{
int sol1 = bestCut(i-1,totalLength);
int sol2 = bestCut(i - 1, totalLength - length[i]) + price[i];
// check whether the optimal solution coming from picking the object or not .
if(sol1>sol2){
printSolution(i-1, totalLength);
}else{
pickedObjects.add(i);
printSolution(i-1, totalLength - length[i]);
}
}
}
public static void main(String[] args) {
System.out.println("Given total rod length : " + totalLength);
System.out.println("Maximum income : "
+ bestCut(price.length - 1, totalLength));
System.out.println("Smaller part sets : ");
printSolution(price.length-1, totalLength);
for (Integer i : pickedObjects) {
System.out.println("picked object: "+ i +" length : "+ length[i]+ " price "+ price[i]);
}
}
}
我们只需要进行逆递归并检查您是否获得了构建输出的最佳解决方案。
尽管我认为您可能会在解决方案中添加一些内存,以便它足够快。希望对您有所帮助。
关于java - 带有零件集的背包递归解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30074037/
我有一个 Tizen Edje 文件,它定义了我的布局。其中一个部分是一张图像,其部分名称为“警告”。该项目在边缘文件中设置为可见,并且按预期显示。 我想使用 C 代码隐藏这部分: Evas_Obje
我正在开发一个 Eclipse RPC 项目。我需要保存和恢复所有 View 的所有内容。我没有在我的项目中使用 EMF,因此我无法使用所有 EMF API。 现在我可以使用的是IMemento。 I
我是一名优秀的程序员,十分优秀!