正如标题所示,我需要解决这个难题。
5
9 6
4 6 8
0 7 1 5
我需要找到的路径是从上到下的最大总和,只移动到相邻的孩子。所以这条路径是5-9-6-7,总和为27.
我的代码适用于我自己输入的每一组数据,但是当我使用提供的textFile数据尝试谜题时,我的总和/答案不被接受为正确。
我不能为我的生活弄清楚我的代码有什么问题。有没有我看不到的例外?
public class Triangle
{
public static void main(String[] args) throws IOException
{
File file = new File("Tri.txt");
byte[] bytes = new byte[(int) file.length()];
try{
//Read the file and add all integers into an array with the correct size. Array size is found with number of bytes file.length()
//Parse string to integer
FileInputStream fis = new FileInputStream(file);
fis.read(bytes);
fis.close();
String[] valueStr = new String(bytes).trim().split("\\s+");
int[] list = new int[valueStr.length];
for (int i = 0; i < valueStr.length; i++)
list[i] = Integer.parseInt(valueStr[i]);
System.out.println(computeMaxPath(list));
}
catch(Exception e)
{
e.printStackTrace();
}
}
static int computeMaxPath(int[] list){
//Disregard row number one since it is the root. Start row number count at 2
int rowNumber = 2;
//set the sum to the value of the root.
int sum = list[0];
//selected index begins at the root, index 0
int selectedIndex = 0;
for (int j = 1; j < list.length; j=j+rowNumber)
{
// for every iteration the right child is found by adding the current selected index by z. What is z?
// the left child is of course found in the index -1 of the right child.
// z is the amount of of elements in the triangle's row. Row 3 has 3 elements, 4 has 4, etc.
// For exmaple, if the selectedIndex is index 4, its right child can be found by adding the index to the next row element count.
// 4 + 4 = 8 the right child is in index 8 and left is in index 7
int rightChildIndex = selectedIndex + rowNumber;
int leftChildIndex = selectedIndex + rowNumber - 1;
//set the appropriate index for the greater child's index
selectedIndex = list[rightChildIndex] >= list[leftChildIndex] ? rightChildIndex : leftChildIndex;
//increment the sum of the path
sum = sum + list[selectedIndex];
System.out.println(selectedIndex);
//increment the row number
rowNumber++;
}
return sum;
}
}
基本上,我的算法通过将文本文件中的int字符串添加到数组中来工作。第一个选定的索引当然是根节点。为了找到合适的孩子,我按下一行的长度添加所选索引,并减去1以找到左子索引。
有什么想法吗?
答案 0 :(得分:6)
此算法使用错误的逻辑。在这种情况下,您的算法可以工作,因为它具有使您的算法工作所需的属性,对于其他输入,这显然不是这种情况。例如,考虑以下(极端)示例:
1
1 0
0 0 9
您的算法通过简单地总是选择具有较大总和的子项来工作,因此在这种情况下,您的算法将产生路径{1 , 1 , 0}
,而正确的算法将产生{1 , 0 , 9}
。
正确的算法需要遍历树并搜索所有路径才能找到正确的解决方案:
int findSum(int[] tree , int at_node){
if(at_node >= length(tree))
return 0 //end of the tree, quit recursive search
//maximum-path including node is the path with the greatest sum that includes either the left or right child of the node.
return max(findSum(tree , leftChild(at_node)) ,
findSum(tree , rightChild(at_node)) + tree[at_node]
}
@JohnBollinger提到:
这种从上到下的方法非常简单。但是效率成本。一种更有效,但也更有效的解决方案,只能遍历每个节点一次。在上述算法中,表示每个节点被访问的时间的树看起来像一个pascal的三角形,从而进行2 ^ height
数组查找。最下层的方法只需要height + height - 1 + ... + 1
次查找。
int findSumBottomTop(int[] tree , int height){
//initialize counter for previous level
int[] sums = new int[height + 1]
fill(sums , 0)
//counter for the level counts down to 1 (note that this variable is not 0-based!!!)
int lvl = height
//counter for nodes remaining on the current level (0-based)
int remaining_in_lvl = lvl - 1
//maximum-paths for each node on the current level
int[] next_level = new int[lvl]
//iterate over all nodes of the tree
for(int node = length(tree) - 1; node > -1 ; node--){
int left_max_path = sums[remaining_in_lvl]
int right_max_path = sums[remaining_in_lvl + 1]
next_level[remaining_in_lvl] = max(right_max_path , left_max_path) + tree[node]
//decrement counter for remaining nodes
remaining_in_lvl -= 1
if(remaining_in_lvl == -1){
//end of a level was encountered --> continue with lvl = lvl - 1
lvl--
//update to match length of next
remaining_in_lvl = lvl - 1
//setup maximum-path counters for next level
sums = next_level
next_level = new int[sums.length - 1]
}
//there is exactly one sum remaining, which is the sum of the maximum-path
return sums[0];
}
基本思路如下:
Consider this example tree:
0 ^ 6
0 1 | 3 6
0 1 2 | 1 3 5
0 1 2 3 | 0 1 2 3
0 0 0 0 0
tree traversal sums
总和将是为每个级别生成的总和的值。我们只是从底部开始搜索并搜索从一个级别中的每个节点到底部的最大路径。这将是左子项的最大路径和右子项的最大路径+节点值的最大值。
答案 1 :(得分:0)
如果行数没有限制,例如,输入可以有数百行。值得像directed acyclic graph一样实现它,然后使用algorithm to find the largest path
答案 2 :(得分:0)
试试这个。
SurfaceView
答案 3 :(得分:0)
这是我最喜欢的Project Euler问题之一(#18)。仅供参考,这是Haskell语言中完整的自下而上的解决方案:
f = foldr (\a b -> let c = zipWith (+) a b
in if null (drop 1 c)
then c
else zipWith max c (tail c)) (repeat 0)
main = print (f z) where
z = map (map read . words) (lines s) :: [[Int]]