LeetCode - 120. Triangle - 思路详解 - C++
2017-01-17 23:18
387 查看
题目
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).
翻译
假设有个三角形。找出从顶部到底部的最小路径。每一步你可以移动到下层的相邻的位置。举例下图,假设有三角形。
最小的路径为11,【2+3+5+1 = 11】
思路
要求最小路径。我们首先分析,走到第i层,必然从第i-1层到来。即要求最小值,可以用公式min( a[i-1][j]+a[i][j],a[i-1][j] + a[j][j+1] ) (0 <= j < n;n 位第i层的数的个数;i表示层数)。
其实这里可以看出这是一道典型的动态规划的问题。
代码
class Solution { public: int minimumTotal(vector<vector<int>>& triangle) { int n = triangle.size(); //用来存储计算中间结果 vector<int> buf(n,0); int res = 0; for(int i = n-1; i> 0; i-- ){ for(int j = 0; j < i; j ++){ buf[j] = min(triangle[i][j],triangle[i][j+1]); } for(int j = 0; j < i; j++){ triangle[i-1][j] += buf[j]; } } return triangle[0][0]; } };
相关文章推荐
- LeetCode - 462. Minimum Moves to Equal Array Elements II - 思路详解 - C++
- LeetCode - 123. Best Time to Buy and Sell Stock III - 思路详解 - C++
- LeetCode- 238. Product of Array Except Self - 思路详解 -C++
- LeetCode - 216. Combination Sum III - 思路详解 - C++
- LeetCode - 217. Contains Duplicate - 思路详解 - C++
- LeetCode - 152. Maximum Product Subarray - 思路详解 - C++
- LeetCode-38. Count and Say-思路详解-C++
- LeetCode - 283. Move Zeroes - 思路详解 - C++
- LeetCode - 482. License Key Formatting - 思路详解 -C++
- LeetCode - 162. Find Peak Element - 思路详解 - C++
- LeetCode - 121. Best Time to Buy and Sell Stock - 思路详解 - C++
- LeetCode-399. Evaluate Division-思路详解-C++
- LeetCode - 414. Third Maximum Number-思路详解- C++
- LeetCode-268. Missing Number-思路详解-C++
- LeetCode-386. Lexicographical Numbers-思路详解-C++
- LeetCode - 122. Best Time to Buy and Sell Stock II - 思路详解 - C++
- Leetcode-442. Find All Duplicates in an Array-思路详解-C++
- LeetCode- 1. Two Sum - 思路详解-C++
- LeetCode - 228. Summary Ranges - 思路详解- C++
- LeetCode - 153. Find Minimum in Rotated Sorted Array - 思路详解- C++