给定一个由数字组成的三角形,从顶至底找出路径最小和。

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, wheren is the total number of rows in the triangle.

思路一:递归,要求以某个数为起点的最小和,可以先求出以跟它相邻的下一层的两个数为起点的最小和,然后取两者的更小者,最后与该数相加即可。基于此可以写出下面的代码:

class Solution {
public:
int minimumTotal(vector<vector<int> > &triangle)
{
// Start typing your C/C++ solution below
// DO NOT write int main() function
return minimumTotal(triangle,0,0);
} int minimumTotal(vector<vector<int> > &triangle, int i, int j)
{
if(i == triangle.size()-1)
return triangle[i][j]; int sum0 = minimumTotal(triangle,i+1,j);
int sum1 = minimumTotal(triangle,i+1,j+1); return min(sum0,sum1) + triangle[i][j];
}
};

可以看到代码简洁易懂,不过在Judge large时超时,原因是重复计算了很多子问题,优化它的思路就是用DP,思想是把先把子问题计算好,供查询使用。下面贴上优化的代码:

class Solution
{
public:
int minimumTotal(vector<vector<int> > &triangle)
{
// Start typing your C/C++ solution below
// DO NOT write int main() function
// 分配空间
int numRow = triangle.size();
vector<vector<int> > ibuffer;
ibuffer.resize(numRow);
for (int i=0; i<numRow; ++i)
ibuffer[i].resize(numRow); // 从底到顶计算最小和
for (int i=numRow-1; i>=0; --i)
{
vector<int> &row = triangle[i]; for (int j=0; j<row.size(); ++j)
{
if(i==numRow-1)
ibuffer[i][j] = row[j];
else
ibuffer[i][j] = min(row[j]+ibuffer[i+1][j], row[j]+ibuffer[i+1][j+1]);
}
} return ibuffer[0][0];
}
};

上面的代码可以通过Large judge。不过开了一个n*n大小的二维数组,因此空间复杂度为O(n^2),n为三角形的层数。进一步观察发现,开二维数组没有必要,因为每次计算只会查询下一层的计算结果,下下层及更后层的计算结果不会使用到,因此可以只开个大小为n的一维数组就可以了。最终代码如下:

class Solution
{
public:
int minimumTotal(vector<vector<int> > &triangle)
{
// Start typing your C/C++ solution below
// DO NOT write int main() function
// 分配空间
int numRow = triangle.size();
vector<int> ibuffer;
ibuffer.resize(numRow); // 从底到顶计算最小和
for (int i=numRow-1; i>=0; --i)
{
vector<int> &row = triangle[i]; for (int j=0; j<row.size(); ++j)
{
if(i==numRow-1)
ibuffer[j] = row[j];
else
ibuffer[j] = min(row[j]+ibuffer[j], row[j]+ibuffer[j+1]);
}
} return ibuffer[0];
}
};

空间复杂度为O(n),n为三角形的层数,时间复杂度为O(K),K为整个三角形中数字的个数。

【Leetcode】Triangle的更多相关文章

  1. 【LeetCode】Triangle 解决报告

    [称号] Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjac ...

  2. 【leetcode】Triangle (#120)

    Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent n ...

  3. 【leetcode】triangle(easy)

    Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent n ...

  4. 【Leetcode】Pascal&#39;s Triangle II

    Given an index k, return the kth row of the Pascal's triangle. For example, given k = 3, Return [1,3 ...

  5. 【LeetCode】Pascal's Triangle II 解题报告

    [LeetCode]Pascal's Triangle II 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/pascals-tr ...

  6. 【LeetCode】120. Triangle 解题报告(Python)

    [LeetCode]120. Triangle 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址htt ...

  7. 【LeetCode】Minimum Depth of Binary Tree 二叉树的最小深度 java

    [LeetCode]Minimum Depth of Binary Tree Given a binary tree, find its minimum depth. The minimum dept ...

  8. 53. Maximum Subarray【leetcode】

    53. Maximum Subarray[leetcode] Find the contiguous subarray within an array (containing at least one ...

  9. 27. Remove Element【leetcode】

    27. Remove Element[leetcode] Given an array and a value, remove all instances of that value in place ...

随机推荐

  1. Spark学习之RDD的理解

    转自:http://www.infoq.com/cn/articles/spark-core-rdd/ 感谢张逸老师的无私分享 RDD,全称为Resilient Distributed Dataset ...

  2. jQuery 图表

    开源网jQuery图表: http://www.oschina.net/project/tag/275/jquery-chart jqGrid(表格) 官网: http://www.jqgrid.co ...

  3. 原生js倒计时和显示当前时间

    <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content ...

  4. 排序算法——交换排序(冒泡排序、快速排序)(java)

    一.冒泡排序 时间复杂度:O(n^2) 公认最慢的排序,每次把最大/最小的放一边,原理: [57,68,59,52] [57,68,59,52] [57,59,68,52] [57,59,52,68] ...

  5. Python中初始化的问题以及注释问题

    #coding=utf-8 # __author__ = 'minmin' from Tkinter import * #创建一个基于Frame的Application类 class Applicat ...

  6. K-Modes算法[聚类算法]

    聚类算法k-Modes的实现 <?php /* *Kmodes算法(聚类算法的实现) */ /* *获取簇的数目 */ //----------------------------------- ...

  7. yii2.0 控制器方法 视图表单 Form表单处理

    假设我们在ArticleController.php下面的actionForm方法中来处理提交的表单 新建立一个 views/Article/article-form.php文件用来作为输入表单 &l ...

  8. 在python文本编辑器里如何设置Tab为4个空格

    python中缩进一般为四个空格,我总结3种常用编辑器中种如何设置Tab键为四个空格 第一种:下载python3.5时自带de 一个IDLE编辑器 在Options选项下的Configure IDLE ...

  9. java中常用的数据加密算法

    以下为加密的工具类: import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; im ...

  10. [问题解决] File "/struts-tags" not found

    错误:org.apache.jasper.JasperException: File "/struts-tags" not found 发生场景:tomcat服务器 解决方案:将t ...