java - 蛮力耗尽内存空间
问题描述
我正忙于创建一个蛮力 TSP 算法,该程序当前工作并计算我输入的最短路径。遗憾的是,我可以使用的最大节点数是 10,这是因为每当我更高时,我都会得到:“Java.lang.OutofMemoryError: Java heap space”。我一直在尝试优化代码,但结果可以忽略不计。如何进一步优化我的代码,以便在运行算法时使用更多节点?
这是我的代码:
import com.sybrand.TSP.*;
import java.util.*;
public class BruteForce extends TSP_Algorithm {
private ArrayList<Coordinate> sortedCoords = new ArrayList<>();
ArrayList<Coordinate> coords = new ArrayList<>();
ArrayList<Coordinate> shortestRoute;
public BruteForce(ArrayList<Coordinate> coords) {
sortedCoords.addAll(coords);
permutation(sortedCoords);
}
public void permutation(ArrayList<Coordinate> nums) {
List<List<Coordinate>> accum = new ArrayList<>();
permutation(accum, Collections.emptyList(), nums);
float shortestDistance = 0.0f;
for (List<Coordinate> routeOption: accum) {
Path calcDistance = new Path((ArrayList<Coordinate>) routeOption);
if (shortestDistance == 0.0f || calcDistance.getDistance() < shortestDistance) {
shortestDistance = calcDistance.getDistance();
this.shortestRoute = (ArrayList<Coordinate>) routeOption;
}
}
}
private static void permutation(List<List<Coordinate>> accum, List<Coordinate> prefix, List<Coordinate> nums) {
int n = nums.size();
if (n == 0) {
accum.add(prefix);
} else {
for (int i = 0; i < n; ++i) {
List<Coordinate> newPrefix = new ArrayList<>(prefix);
newPrefix.add(nums.get(i));
List<Coordinate> numsLeft = new ArrayList<>(nums);
numsLeft.remove(i);
permutation(accum, newPrefix, numsLeft);
}
}
}
public ArrayList<Coordinate> getSortedCoordinates() {
return shortestRoute;
}
}
解决方案
推荐阅读
- cmd - 如何使用命令行重命名 Windows 10 机器
- sql - 具有大量值的 SQL 查询 IN 子句
- angular - 没有常春藤的Angular 10库
- java - 如何在没有清单的情况下以编程方式初始化 Admob 应用程序 ID
- php - 如何在 Wordpress 中覆盖父模板的页脚?
- node.js - 什么是icu4c,是否需要添加到PATH?
- android - 如何修复 RecyclerView 不能为空
- python - 是否有一个熊猫函数可以将例如前三行连接在一起(就像我有一个长度为三的窗口)
- node.js - npm 错误!cb() 从未调用过
- azure-devops - Terraform:将消息添加到队列