LeetCode 120 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).
思考過程
看到題目注意一句話“Each step you may move to adjacent numbers on the row below.”,就是說每一步只能往下一層中相鄰的數字走。
一開始想從上到下建立一個陣列d[i][j],表示到達第i行j列的數字的最小和。用兩層for迴圈然後判斷每個數字上一層的兩個相關數字的最小和,取較小的加上本身作為d(注意不能越界)。然後這麼做多了很多判斷以及不知道動規的意義何在,,,
所以得換個思路從下往上遍歷,每個位置的最小和(從下往上加)等於其下層相鄰兩個數字之中較小的最小和,直接從倒數第二行開始累加,於是狀態轉移方程:
triangle[i][j]+=min(triangle[i+1][j+1], triangle[i+1][j]);
然後有:
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
for(int i = triangle.size()-2; i >= 0; i--){
for(int j = 0; j < triangle[i].size();j++){
triangle[i][j]+=min(triangle[i+1][j+1], triangle[i+1][j]);
}
}
return triangle[0][0];
}
};
相關文章
- [LeetCode] 120. TriangleLeetCode
- Leetcode 120. TriangleLeetCode
- LeetCode解題報告 120. Triangle [medium]LeetCode
- Leetcode TriangleLeetCode
- Leetcode-TriangleLeetCode
- Triangle leetcode javaLeetCodeJava
- Leetcode Pascal's TriangleLeetCode
- leetcode Pascal's Triangle IILeetCode
- Leetcode-Pascal's TriangleLeetCode
- Leetcode-Pascal's Triangle IILeetCode
- Pascal's Triangle II Leetcode javaLeetCodeJava
- Leetcode 611 javascript Valid Triangle NumberLeetCodeJavaScript
- Pascal's Triangle leetcode java(楊輝三角)LeetCodeJava
- 【LeetCode從零單排】No118 Pascal's TriangleLeetCode
- 976. Largest Perimeter Triangle(Leetcode每日一題-2020.11.29)LeetCode每日一題
- leetcode 120 三角形最小路徑和LeetCode
- Windows下編譯TriangleWindows編譯
- 每天一道LeetCode--118. Pascal's Triangle(楊輝三角)LeetCode
- 【Leetcode】120.三角形最小路徑和LeetCode
- [Leetcode]120.三角形路徑最小和LeetCode
- LeetCode-120-三角形最小路徑和LeetCode
- 每天一道LeetCode--119.Pascal's Triangle II(楊輝三角)LeetCode
- LINUX下編譯TriangleLinux編譯
- 【博弈論】HDU - 7216 Triangle GameGAM
- 【Lintcode】359. Make Equilateral TriangleUI
- CF1991F Triangle Formation 題解ORM
- System Monitor Process (SMON) (120)
- Camera List Record - 120
- 我的收藏週刊120
- Codeforces Round #195 (Div. 2) A. Vasily the Bear and Triangle
- A C++ half-edge data structure for a triangle mesh with no external dependencies whatsoeveC++Struct
- PostgreSQL DBA(120) - pgAdmin(HA with Patroni)SQL
- 是男人就上120層破解教程
- 基於Starter G120除錯除錯
- 120 C++中的物件指標C++物件指標
- CX4-120 建立儲存組
- BUUCTF-Misc(111-120)
- ZOJ Monthly, January 2019 - A Little Sub and Pascal's Triangle(找規律)