首页 > 代码库 > Triangle
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).
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.
分析:该题可以用暴力搜索的方式将所有path的和存在一个vector中,但这样的空间复杂度是O(2^n)。为了使空间复杂度降到O(n),我们可以用动态规划里record的方式,这里的record我们只需记录到上一行每个位置path的最小sum,然后通过这个计算到本行每个位置path的最小sum。代码如下:
1 class Solution { 2 public: 3 int minimumTotal(vector<vector<int> > &triangle) { 4 vector<int> pre_sum, cur_sum; 5 pre_sum.push_back(triangle[0][0]); 6 cur_sum.push_back(triangle[0][0]); 7 for(int i = 1; i < triangle.size(); i++){ 8 cur_sum.clear(); 9 for(int j = 0; j < triangle[i].size(); j++){10 if(j == 0) cur_sum.push_back(pre_sum[0]+triangle[i][j]);11 else if(j == triangle[i].size()-1) cur_sum.push_back(pre_sum.back()+triangle[i][j]);12 else cur_sum.push_back(min(pre_sum[j-1]+triangle[i][j],pre_sum[j]+triangle[i][j]));13 }14 pre_sum = cur_sum;15 }16 return *min_element(cur_sum.begin(),cur_sum.end());17 }18 };
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。