题目:

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

代码:

class Solution {
public:
int minimumTotal(vector<vector<int> > &triangle) {
if (triangle.size()<) return ;
int min_sum = triangle[][];
for ( int i = ; i<triangle.size(); ++i )
{
for (int j = ; j<triangle[i].size(); ++j )
{
if (j==triangle[i].size()-)
{
triangle[i][j] += triangle[i-][j-];
min_sum = std::min(min_sum, triangle[i][j]);
}
else if ( j== )
{
triangle[i][] += triangle[i-][];
min_sum = triangle[i][j];
}
else
{
triangle[i][j] += std::min(triangle[i-][j-], triangle[i-][j]);
min_sum = std::min(min_sum, triangle[i][j]);
} }
}
return min_sum;
}
};

tips:

这种做法时间复杂度O(n),空间复杂度O(1)。

思路很简单,就是遍历每层元素的同时,把这一个元素的值更新为走到该位置的最小路径和。

min_sum这个遍历记录当前最小值,其实只有当遍历到最后一层的时候才有用,偷懒就没有改动了。

但是有个缺点就是把原来的triangle的结构都破坏了,研究一下用O(n)额外空间,但不破坏原有triangle的做法。

=======================================

似乎脑子里有印象:遍历每层数组的时候,可以从后往前算,可以比较顺畅。顺着思路,就写了下面的代码,不破坏triangle的原有结构,也可以在O(n)额外空间的条件下AC。

class Solution {
public:
int minimumTotal(vector<vector<int> > &triangle) {
if (triangle.size()<) return ;
vector<int> extra(triangle.size(),INT_MAX);
extra[] = triangle[][];
for ( int i = ; i<triangle.size(); ++i )
{
for ( int j = triangle[i].size()-; j>=; --j )
{
if ( j== )
{
extra[j] = triangle[i][j] + extra[];
}
else
{
extra[j] = triangle[i][j] + std::min(extra[j-], extra[j]);
}
}
}
int min_sum = extra[];
for ( int i = ; i < extra.size(); ++i ) min_sum = std::min(min_sum, extra[i]);
return min_sum;
}
};

tips:

这里开一个额外vector(即extra),大小为n,数组元素初值都设为INT_MAX(后面解释为什么要设为INT_MAX)。

extra用来存放“到当前层的各个位置的最短路径长度和是多少”。

为什么遍历每层都要从后往前遍历呢?

举例说明如下:

以原题给的case为例

i = 1时

extra == [2,INT_MAX...]

triangle[1] == [3,4]

观察两种遍历triangle[1]的方向:

a) 先遍历triangle[1][0]则更新extra[0]为5,即extra == [5,INT_MAX...]

b) 这时,再遍历triangle[1][1],判断extra[0]与extra[1]哪个小,再与triangle[1][1]相加,再赋值给extra[1]。

这里问题就凸显出来了,此时extra[0]已经不是最开始的2了,已经被我们更新过后丢掉了(此时可以采用补救措施,例如添加一个中间变量tmp之类的)。

现在换一种思路,改变遍历triangle[1]的方向

a) 遍历triangle[1][1],则更新extra[1]为6

b) 这时再遍历triangle[1][0],更新extra[0]为extra[0]+triangle[1][0]=5;结果正确。

这样对比就可以看出来从后向前遍历的好处,因为下一层的数组总比上一层的数组多出来一个元素;因此再更新时,先更新extra的最后一个位置并没有影响到上一轮extra得到的结果(于是也就不用什么tmp中间变量之类的了)。

还有一个细节没有说:为啥初始化extra的时候都初始化为INT_MAX呢?这是为了代码的优雅性。

通过题意我们可以知道,其实每层的最后一个元素j只能由上一层的的最后一个元素j-1得来。

为了保持“extra[j] = triangle[i][j] + std::min(extra[j-1], extra[j]);”的优雅性,因此初始化为INT_MAX;如果j==triangle[i].size()-1的时候,我们已经知道一定是选择extra[j-1]而不是extra[j],因为此时的extra[j]就是INT_MAX。

这样一来,只用处理j==0的一种corner case了。

=================================

看到一种更屌爆的做法,完全不用判断各种corner case,思路如下:

从下往上遍历,牺牲triangle的原有结构。

======================================

第二次过这道题,用O(n)复杂度,单独处理最左边的元素。

class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
if ( triangle.empty() ) return ;
vector<int> minPath(triangle.size(),INT_MAX);
minPath[] = triangle[][];
for ( int i=; i<triangle.size(); ++i )
{
for ( int j=triangle[i].size()-; j>; --j )
{
minPath[j] = min(minPath[j-], minPath[j]) + triangle[i][j];
}
minPath[] += triangle[i][];
}
int ret = minPath[];
for ( int i=; i<minPath.size(); ++i ) ret = min(ret, minPath[i]);
return ret; }
};

【Triangle 】cpp的更多相关文章

  1. 【Pascal's Triangle】cpp

    题目: Given numRows, generate the first numRows of Pascal's triangle. For example, given numRows = 5,R ...

  2. leetcode 【 Triangle 】python 实现

    题目: Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjace ...

  3. 【Permutations】cpp

    题目: Given a collection of numbers, return all possible permutations. For example,[1,2,3] have the fo ...

  4. 【Subsets】cpp

    题目: Given a set of distinct integers, nums, return all possible subsets. Note: Elements in a subset ...

  5. 【Anagrams】 cpp

    题目: Given an array of strings, return all groups of strings that are anagrams. Note: All inputs will ...

  6. 蓝桥杯 【dp?】.cpp

    题意: 给出一个2*n的方格,当刷完某一个方格的漆后可以且只可以走到相邻的任何一格,即上 下 左 右 左上 左下 右上 右下.可以从任意一个格子开始刷墙,问有多少种刷法,因为随着n的增大方案数会变多, ...

  7. 【N-Queens】cpp

    题目: The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two que ...

  8. 【Combinations】cpp

    题目: Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. For ex ...

  9. 【Candy】cpp

    题目: There are N children standing in a line. Each child is assigned a rating value. You are giving c ...

随机推荐

  1. swagger + springboot

    参考文章:  https://blog.csdn.net/xupeng874395012/article/details/68946676/ https://blog.csdn.net/hry2015 ...

  2. 利用binlog2sql解析mysqlbinlog row行日志

    binlog2sql 项目作者:曹单锋 github项目地址:https://github.com/danfengcao/binlog2sql 也可在github.com上搜索“binlog2sql” ...

  3. Python常见编程规范总结

    Pythonic定义 Python最常用的编码风格还是PEP8,详见:http://jython.cn/dev/peps/pep-0008/ Pythonic确实很难定义,先简单引用下<Pyth ...

  4. 关于C#的垃圾回收机制,Finalize和Dispose的区别(自认为很清晰了,有疑问的评论)

    来到个新地方,新学习C#,前面看到C#的垃圾回收,Finalize和Dispose时,总是一知半解,迷迷糊糊.这次好了,前面连续两次面试问到这个问题,脑子里不是很清晰,加上用英文来表达,更是雪上加霜的 ...

  5. c++连接mysql并提示“无法解析的外部符号 _mysql_server_init@12”解决方法&提示缺少“libmysql.dll”

    课程作业要用c++连接mysql server,但是出现些小问题,经查阅资料已经解决,做一下笔记. 环境:vs2017, mysql版本是8.0.16-winx64. 设置项目属性   项目 -  C ...

  6. 快速开发一个PHP扩展

    快速开发一个PHP扩展 作者:heiyeluren时间:2008-12-5博客:http://blog.csdn.net/heiyeshuwu 本文通过非常快速的方式讲解了如何制作一个PHP 5.2 ...

  7. python3安装pip

    wget --no-check-certificate https://pypi.python.org/packages/source/p/pip/pip-8.0.2.tar.gz#md5=3a73c ...

  8. shell脚本,awk结合正则来打印文件里面的内容。

    文件内容如下:key1abc d key2 1.想得到如下结果: abc d 2.想得到如下结果: key1key2

  9. Oracle下如何收集 Systemstate dump

    2: dump (不包括lock element) 10: dump 11: dump + global cache of RAC 256: short stack (函数堆栈) 258: 256+2 ...

  10. 自动布局之-NSLayoutConstraint

    AutoLayout概念是苹果自iOS6开始引入的概念. 目前为止,实现自动布局技术选型方面也可以使用xib和storyboard.在开发过程中通常登录.注册等变动可能性较小的视图,我会采用xib开发 ...