[Leetcode] triangle

Source: Internet
Author: User
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 is11(I. e., 2 + 3 + 5 + 1 = 11 ).

Note:
Bonus Point if you are able to do this using onlyO(N) Extra space, whereNIs the total number of rows in the triangle.

Algorithm ideas:

Thought 1:

From top to bottom, use an array to record the weighted situation of all nodes from the root node to the I layer. When you fall to the last layer, you can find the shortest path. Requires O (n) space.

Not Implemented

 

Idea 2:

 1     public int minimumTotal(List<List<Integer>> triangle) { 2         if(triangle == null || triangle.size() == 0) return 0; 3         int height = triangle.size(); 4         for(int i = height - 2; i >= 0; i--){ 5             List<Integer> list = triangle.get(i); 6             for(int j = 0; j < list.size();j++){ 7                 int min = triangle.get(i + 1).get(j) < triangle.get(i + 1).get(j + 1) ? triangle.get(i + 1).get(j) : triangle.get(i + 1).get(j + 1);   8                 list.set(j, list.get(j) + min); 9             }10         }11         return triangle.get(0).get(0);12     }

This code was previously seen and very powerful.

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.