Leetcode: Triangle
I. Question
[
[2],
[3, 4],
[6, 5, 7],
[4, 1, 8, 3]
]
In a triangle two-dimensional array, there is a series of numbers to find the path from the top layer to the bottom layer of the minimum sum.
Ii. Analysis
Solution 1 recursively solves the problem by finding the minimum sum starting from a certain number. You can first find the minimum sum of the two numbers next layer adjacent to it as the starting point, and then take the smaller of the two, add the value to the number. However, this method times out.
// Recursion, timeout class Solution {public: int minimumTotal (vector
> & Triangle) {return minimumTotal (triangle, 0, 0);} int minimumTotal (vector
> & Triangle, int row, int col) {if (row = triangle. size ()-1) return triangle [row] [col]; return min (minimumTotal (triangle, row + 1, col), minimumTotal (triangle, row + 1, col + 1) + triangle [row] [col] ;}};
Idea 2 is obviously a question of dynamic planning. Find the minimum path and of a triangle two-dimensional array from top to bottom. Maintain the minimum path and value of an element. Then, the minimum path of a element I and j is the minimum path of the adjacent two elements corresponding to the upper layer and the value of its own, the recursive formula is ans [I] [j] = min (ans [I-1] [J-1], ans [I-1] [j]) + triangle [I] [j]. Scan the paths and values of the last layer to obtain the minimum value. Each element needs to be maintained once. There are 1 + 2 +... + n = n * (n + 1)/2 elements in total. The time complexity is O (n ^ 2 ). In space, you only need to maintain one layer at a time (because the current layer only uses the elements of the previous layer), so the space complexity is O (n ).
Class Solution {public: int minimumTotal (vector
> & Triangle) {int len = triangle. size (); if (len = 0) return 0; if (len = 1) return triangle [0] [0]; int ans [len]; ans [0] = triangle [0] [0]; for (int I = 1; I
= 1; j --) ans [j] = min (ans [j], ans [J-1]) + triangle [I] [j]; ans [0] = ans [0] + triangle [I] [0];} int minLen = ans [0]; for (int I = 1; I
Thought 3: from another perspective, if this question is not dynamically planned from top to bottom, but from bottom to bottom, recursion is only used to change the minimum path of two adjacent elements corresponding to the next layer and add their own values. The principle is the same as the above method, in this way, the advantage is that you do not need to find the smallest path, and the first and last elements do not need to be processed separately.
Class Solution {public: int minimumTotal (vector
> & Triangle) {int len = triangle. size (); if (len = 0) return 0; // vector
Ans (len); // the same effect as int ans [len]; // set the underlying initial for (int I = 0; I
= 0; I --) {for (int j = 0; j <= I; j ++) {ans [j] = min (ans [j], ans [j + 1]) + triangle [I] [j] ;}} return ans [0] ;}};