https://leetcode.com/problems/triangle/description/
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).
今天仔細分析了HashMap,又理清了推薦系統的思路,很有成就感,我發現還是需要專注的,心無旁騖地分析一件事情才能很快做出來。
對于這道題,跟那個Pascal's三角的排列差不多,我們要把他左對齊的話就容易找規律了。
[
[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).
這道題如果沒有 Each step you may move to adjacent numbers on the row below這個條件的話就是簡單的找最小值就行了,多了這個條件就成了動態規劃。我對動態規劃的印象是,類似Paths那道題,空間換時間。也就是把目前為止所有格子的minimum path計算出來。
這道題的狀態轉移方程我試著寫一下:
paths[i][j] = nums[i][j] + min{paths[i-1][j-1], paths[i-1][j]}
這方程的前提是掐頭去尾。
花了半小時寫代碼,調試了好幾次才AC..不過我感覺自己有點懂動歸了。
public class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
//第一列和最后一列的path sum
for (int i = 1; i < triangle.size(); i++) {
triangle.get(i).set(0, triangle.get(i - 1).get(0) + triangle.get(i).get(0));
int cell_size = triangle.get(i).size();
triangle.get(i).set(cell_size - 1, triangle.get(i - 1).get(cell_size - 2) + triangle.get(i).get(cell_size - 1));
}
//第三行開始
for (int i = 2; i < triangle.size(); i++)
//每一行的第二個數到倒數第二個數
for (int j = 1; j < triangle.get(i).size() - 1; j++) {
triangle.get(i).set(j, triangle.get(i).get(j) + Math.min(triangle.get(i - 1).get(j - 1), triangle.get(i - 1).get(j)));
}
//min要定義成最后一行第一個數
int min = triangle.get(triangle.size() - 1).get(0);
for (int i = 0; i < triangle.get(triangle.size() - 1).size(); i++) {
if (min > triangle.get(triangle.size() - 1).get(i))
min = triangle.get(triangle.size() - 1).get(i);
}
return min;
}
}
寫的過程中犯的幾個錯誤:
triangle.get(i).set(cell_size - 1, triangle.get(i - 1).get(cell_size - 2) + triangle.get(i).get(cell_size - 1));
cell_size - 2寫成了size-1。
triangle.get(i).set(j, triangle.get(i).get(j) + Math.min(triangle.get(i - 1).get(j - 1), triangle.get(i - 1).get(j)));
狀態轉移方程忘了加上triangle.get(i).get(j)了。。
- 把 int min = triangle.get(triangle.size() - 1).get(0);初始化成了Integer.MIN_VALUE.