Triangle @ LeetCode

Source: Internet
Author: User

Package Level3; import java. util. arrayList;/*** Triangle * Given a triangle, find the minimum path sum from top to bottom. each step you may move to adjacent numbers on the row below. for example, given the following triangle [[2], [3, 4], [6, 5, 7], [4, 1, 8, 3] The minimum path sum from top to bottom is 11 (I. e ., 2 + 3 + 5 + 1 = 11 ). note: Bonus point if you are able to do this using only O (n) extra space, where n is the total number of rows in the triangle. **/public class S120 {public static void main (String [] args) {} public int minimumTotal (ArrayList <Integer> triangle) {int rowLen = triangle. size (); // The dp array is used to store the optimal int for each grid [] [] sum = new int [rowLen] [rowLen]; // The bottom row of ArrayList <Integer> last = triangle. get (triangle. size ()-1); for (int I = 0; I <last. size (); I ++) {sum [rowLen-1] [I] = last. get (I);} // Bottom-up DP for (int I = rowLen-2; I> = 0; I --) {ArrayList <Integer> row = triangle. get (I); for (int j = 0; j <= I; j ++) {sum [I] [j] = Math. min (sum [I + 1] [j], sum [I + 1] [j + 1]) + row. get (j) ;}} return sum [0] [0] ;}}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.