1. 程式人生 > >LeetCode——Triangle

LeetCode——Triangle

content path clas 給定 1.4 ble triangle mon pro

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.

原題鏈接:https://oj.leetcode.com/problems/triangle/

題目:給定一個三角形。找出從頂部究竟部的最短路徑和。每一步你能夠移動到下一行的鄰接數字。

思路:最初的理解是:最短路徑和能夠看成是找出每一行中的最小值。最後求和。

	public int minimumTotal1(List<List<Integer>> triangle) {
		int sum = 0;
		for (int i = 0; i < triangle.size(); i++) {
			int min = triangle.get(i).get(0);
			for (int j = 0; j < triangle.get(i).size(); j++) {
				if (triangle.get(i).get(j) < min)
					min = triangle.get(i).get(j);
			}
			sum += min;
		}
		return sum;
	}

提交後發現錯了。要是這樣也太簡單了。

要求的並非每行的最小值,而應該這樣理解:到達每一個元素的最小路徑和為到上一層與它相鄰兩個元素最短路徑和中較小者加上該元素的值。

所以,解法能夠例如以下:

	public int minimumTotal(List<List<Integer>> triangle) {
	    for(int i = triangle.size() - 2; i >= 0; i--)
	    {
	        for(int j = 0; j < triangle.get(i).size(); j++)
	        {
	            triangle.get(i).set(j, triangle.get(i).get(j) + Math.min(triangle.get(i + 1).get(j), triangle.get(i + 1).get(j + 1)));
	        }
	    }
	    return triangle.get(0).get(0);
	}

reference : http://www.douban.com/note/272435660/


LeetCode——Triangle