最大路径和

从下面展现的三角形的顶端出发,不断移动到下一行与其相邻的元素,可以获得的最大路径和数组

        3spa

        7    4code

         2    4    6blog

        8    5    9    3递归

如上图,最大路径和为3 + 7 + 4 + 9 = 23it

求从下面展现的三角形顶端出发到达底部,可以获得的最大路径和:io

                        

15 
47 , 62 
26 , 71 , 37
81 , 55 , 40 , 17
17 , 66 , 54 , 66 , 10
31 , 66 , 37 , 54 , 52 , 10
72 , 39 , 85 , 57 , 78 , 17 , 63
71 , 96 , 70 , 81 , 68 , 79 , 18 , 13
29 , 31 , 40 , 96 , 67 , 3 , 10 , 82 , 49
58 , 65 , 73 , 90 , 30 , 76 , 24 , 71 , 51 , 67
87 , 55 , 52 , 85 , 38 , 8 , 43 , 11 , 32 , 20 , 79
44 , 10 , 6 , 56 , 33 , 5 , 26 , 34 , 34 , 1 , 83 , 66
44 , 28 , 54 , 25 , 2 , 20 , 57 , 23 , 43 , 40 , 12 , 49 , 58class

 

 

 

 

 

 

答案是:15 + 62 + 71 + 55 + 66 + 66 + 85 + 81 + 96 + 90 + 85 + 56 + 25 = 853test

程序:程序

 1 static int[] array = {
 2             15 , 
 3             47 , 62 , 
 4             26 , 71 , 37 , 
 5             81 , 55 , 40 , 17 , 
 6             17 , 66 , 54 , 66 , 10 , 
 7             31 , 66 , 37 , 54 , 52 , 10 , 
 8             72 , 39 , 85 , 57 , 78 , 17 , 63 , 
 9             71 , 96 , 70 , 81 , 68 , 79 , 18 , 13 , 
10             29 , 31 , 40 , 96 , 67 , 3 , 10 , 82 , 49 , 
11             58 , 65 , 73 , 90 , 30 , 76 , 24 , 71 , 51 , 67 , 
12             87 , 55 , 52 , 85 , 38 , 8 , 43 , 11 , 32 , 20 , 79 , 
13             44 , 10 , 6 , 56 , 33 , 5 , 26 , 34 , 34 , 1 , 83 , 66 , 
14             44 , 28 , 54 , 25 , 2 , 20 , 57 , 23 , 43 , 40 , 12 , 49 , 58
15     };
 1     public void testMaxPathSum() {
 2         System.out.println(MaxPathSum(0,0));
 3     }
 4     public int MaxPathSum(int row,int col) {
 5         if(row<13&&col<13) {
 6             int left = MaxPathSum(row+1,col);
 7             int right = MaxPathSum(row+1,col+1);
 8             return array[position(row,col)]+(left>right?left:right);
 9         }
10         return 0;
11     }
12     public int position(int row,int col) {
13         int position = 0;
14         for(int i=0;i<=row;i++) {
15             position +=i;
16         }
17         return position+col;
18     }

 

分析:

实际上是将数组展开成三角形,首先根据行和列计算出在数组中的位置。先计算最低端的,经过往上递归找到最大值。这里的left至关于他左边的那天路径,right至关于他右边的路径

相关文章
相关标签/搜索