Recursive version: It's a pity that it's TLE.
Package p1163; import Java. io. file; import Java. io. filenotfoundexception; import Java. util. extends; public class main {static int COUNT = 105; static int d [] [] = new int [count] [count]; static int N; public static void main (string [] ARGs) throws filenotfoundexception {// file F = new file ("C: \ data.txt "); // specify CIN = new partition (f); Specify CIN = new partition (system. in); n = cin. nextint (); For (INT I = 1; I <= N; I ++) {for (Int J = 1; j <= I; j ++) {d [I] [J] = cin. nextint () ;}} system. out. println (func (1, 1);} // row I, column J, j <= istatic int func (int I, Int J) {int max = 0; if (I <n) {max = d [I] [J] + max (func (I + 1, J), func (I + 1, J + 1 )); // down, to the right} else {max = d [I] [J];} return Max;} static int max (int A, int B) {return A> B? A: B ;}}
For a moment, the main reason for TLE is that recursion is calculated from top to bottom. Then, use the motion gauge to calculate from the bottom up.
-------------------------------------------------------------------------- --------------------------------------------------------------------------
Dynamic version:
Import Java. io. file; import Java. io. filenotfoundexception; import Java. util. extends; public class main {static int COUNT = 105; static int d [] [] = new int [count] [count]; static int res [] [] = new int [count] [count]; // use res to store the computed data static int N; public static void main (string [] ARGs) throws filenotfoundexception {// file F = new file ("C: \ data.txt "); // convert CIN = new branch (f); Convert CIN = new branch (System. in); n = cin. nextint (); For (INT I = 1; I <= N; I ++) {for (Int J = 1; j <= I; j ++) {d [I] [J] = cin. nextint () ;}}for (INT I = 1; I <= N; I ++) {res [N] [I] = d [N] [I];} // For (INT I = N; I> = 1; I --) {for (Int J = 0; j <= I; j ++) {res [I] [J] = d [I] [J] + max (RES [I + 1] [J], res [I + 1] [J + 1]);} system. out. println (RES [1] [1]); // Finally, the element at the top of the res array is the required maximum value} static int max (int A, int B) {return A> B? A: B ;}}
In fact, there are not many differences between the dynamic rules and the recursive version above. Are calculated from the underlying layer, and then accumulated from the upstream layer. Only the recursive version needs to be recursive many times, so calculate the time returned by recursion.