0
我想开发一个Java程序来解决https://projecteuler.net/problem=18。不过我碰到的困难,我不知道为什么这个代码不工作:最大路径总和
int[][] testTriangle = {
{3},
{7, 4},
{2, 4, 6},
{8, 5, 9, 3}
};
HashMap<Integer, Integer> hasGoneDownRoute = new HashMap<Integer, Integer>(); //Stores numbers and start positions to numbers
int largestValue = 0;
int value = 0;
int row = testTriangle.length-1;
for (int startPosition = 0; startPosition <= testTriangle[row].length-1; startPosition++) { //starts from all possible start positions on the bottom row
for (int y = 1; y<=2; y++) { //executes from the same start position twice to get all possible routes (ACTUALLY THIS MIGHT BE WRONG!?)
while (row != 0) { //until it reaches the top row
if (startPosition == 0) { //if it's on the far left
value += testTriangle[row-1][0];
}
else if (startPosition == testTriangle[row].length-1) { //if at's on the far right
value += testTriangle[row-1][testTriangle[row-1].length-1]; //set the value to the row above it on the far right
}
else { //This never gets called?
int noToChooseFrom1 = testTriangle[row-1][startPosition]; //above it and to the right
int noToChooseFrom2 = testTriangle[row-1][startPosition-1]; //above it and to the left
if (hasGoneDownRoute.containsKey(noToChooseFrom1) && hasGoneDownRoute.get(noToChooseFrom1) == startPosition) { //checks if it has gone down a certain route before
value += noToChooseFrom2;
hasGoneDownRoute.put(testTriangle[row-1][startPosition-1], startPosition);
}
else {
value += noToChooseFrom1;
hasGoneDownRoute.put(noToChooseFrom1, startPosition);
}
}
row--;
}
}
if (value > largestValue) {
largestValue = value;
}
System.out.println(largestValue);
}
我刚添加笔记,试图解释我的思维过程
这是什么输出? – anthropomorphic