题目:

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. RxJava2 中多种取消订阅 dispose 的方法梳理( 源码分析 )

    Github 相关代码: Github地址 一直感觉 RxJava2 的取消订阅有点混乱, 这样也能取消, 那样也能取消, 没能系统起来的感觉就像掉进了盘丝洞, 迷乱… 下面说说这几种情况 几种取消的 ...

  2. Eucalyptus(v4.0)系统需求

    1.计算需求 Physical Machines: All Eucalyptus components must be installed on physical machines, not virt ...

  3. WPF:鼠标长时间无操作,窗口隐藏

    //设置鼠标长时间无操作计时器 private System.Timers.Timer MouseTimerTick = new System.Timers.Timer(10000); private ...

  4. System Center Configuration Manager 2016 域准备篇(Part1)

    本系列指南如何从Microsoft安装最新的Configuration Manager基准版本.较新的可用基准版本System Center Configuration Manager(当前分支)版本 ...

  5. Android商城开发系列(十)—— 首页活动广告布局实现

    在上一篇博客当中,我们讲了频道布局的实现,接下来我们讲解一下活动广告布局的实现,效果如下图: 这个是用viewpager去实现的,新建一个act_item.xml,代码如下所示: <?xml v ...

  6. linux 命令——9 touch (转)

    linux的touch命令不常用,一般在使用make的时候可能会用到,用来修改文件时间戳,或者新建一个不存在的文件. 1.命令格式: touch [选项]... 文件... 2.命令参数: -a    ...

  7. 【BZOJ4540】 [HNOI2016] 序列(莫队)

    点此看题面 大致题意: 求出一个序列的一段区间中所有子序列最小值之和. 莫队 这道题其实是一道莫队题. 但是需要大量的预处理. 预处理 先考虑预处理两个数组\(lst_i\)和\(nxt_i\),分别 ...

  8. python实现二叉树的镜像

    题目描述 操作给定的二叉树,将其变换为源二叉树的镜像. 输入描述: 二叉树的镜像定义:源二叉树 8 / \ 6 10 / \ / \ 5 7 9 11 镜像二叉树 8 / \ 10 6 / \ / \ ...

  9. [vijos1066]弱弱的战壕

    描述 永恒和mx正在玩一个即时战略游戏,名字嘛~~~~~~恕本人记性不好,忘了-_-b. mx在他的基地附近建立了n个战壕,每个战壕都是一个独立的作战单位,射程可以达到无限(“mx不赢定了?!?”永恒 ...

  10. 爬虫学习(六)——异常处理URLerrors异常处理

    # 异常处理都在urllib.error中进行处理 import urllib.requestimport urllib.error # 第一种异常:该网址不存在url = "http:// ...