leetcode面试准备:Triangle

1 题目

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).

接口:public int minimumTotal(List<List<Integer>> triangle)

2 思路

题意

注意是三角形,第i层选了j位置的数,在第i + 1层只能够选jj + 1层的数。

这是一道动态规划的题目,求一个三角形二维数组从顶到低端的最小路径和。思路是维护到某一个元素的最小路径和,那么在某一个元素i,j的最小路径和就是它上层对应的相邻两个元素的最小路径和加上自己的值,递推式是sum[i][j]=min(sum[i-1][j-1],sum[i-1][j])+triangle[i][j]。最后扫描一遍最后一层的路径和,取出最小的即可。每个元素需要维护一次,总共有1+2+...+n=n*(n+1)/2个元素,所以时间复杂度是O(n^2)。而空间上每次只需维护一层即可(因为当前层只用到上一层的元素),所以空间复杂度是O(n)。

上述代码实现时要注意每层第一个和最后一个元素特殊处理一下。

换个角度考虑一下,如果这道题不自顶向下进行动态规划,而是放过来自底向上来规划,递归式只是变成下一层对应的相邻两个元素的最小路径和加上自己的值,原理和上面的方法是相同的,这样考虑到优势在于不需要最后对于所有路径找最小的,而且第一个元素和最后元素也不需要单独处理了,所以代码简洁了很多。代码如下:

3 代码

    // 从上往下想
public int minimumTotal(List<List<Integer>> triangle) {
int size = triangle.size();
if (size == 0)
return 0;
int[] sum = new int[size];
sum[0] = triangle.get(0).get(0);
for (int i = 1; i < size; i++) {
int level = i;
sum[i] = sum[i - 1] + triangle.get(i).get(i);
for (int j = level - 1; j >= 1; j--) {
sum[j] = Math.min(sum[j - 1], sum[j]) + triangle.get(i).get(j);
}
sum[0] = sum[0] + triangle.get(i).get(0);
} // 遍历sum,求最小值
int min = Integer.MAX_VALUE;
for (int s : sum) {
min = Math.min(s, min);
}
return min;
} // 从下往上想
public int minimumTotal1(List<List<Integer>> triangle) {
int size = triangle.size();
if (size == 0)
return 0;
int[] sum = new int[size];
for (int i = 0; i < size; i++) {
sum[i] = triangle.get(size - 1).get(i);
}
for (int i = size - 2; i >= 0; i--) {
int level = i;
for (int j = 0; j <= level; j++) {
sum[j] = Math.min(sum[j], sum[j + 1]) + triangle.get(i).get(j);
}
}
return sum[0];
}

4 总结

一维DP。模型简单,比较适合在电面中出现。

leetcode面试准备:Triangle的更多相关文章

  1. LeetCode:Pascal's Triangle I II

    LeetCode:Pascal's Triangle Given numRows, generate the first numRows of Pascal's triangle. For examp ...

  2. 【LeetCode OJ】Triangle

    Problem Link: http://oj.leetcode.com/problems/triangle/ Let R[][] be a 2D array where R[i][j] (j < ...

  3. leetcode面试准备: Maximal Rectangle

    leetcode面试准备: Maximal Rectangle 1 题目 Given a 2D binary matrix filled with 0's and 1's, find the larg ...

  4. leetcode面试准备: Game of Life

    leetcode面试准备: Game of Life 1 题目 According to the Wikipedia's article: "The Game of Life, also k ...

  5. leetcode面试准备: Word Pattern

    leetcode面试准备: Word Pattern 1 题目 Given a pattern and a string str, find if str follows the same patte ...

  6. leetcode面试准备:Add and Search Word - Data structure design

    leetcode面试准备:Add and Search Word - Data structure design 1 题目 Design a data structure that supports ...

  7. leetcode面试准备:Reverse Words in a String

    leetcode面试准备:Reverse Words in a String 1 题目 Given an input string, reverse the string word by word. ...

  8. leetcode面试准备:Implement Trie (Prefix Tree)

    leetcode面试准备:Implement Trie (Prefix Tree) 1 题目 Implement a trie withinsert, search, and startsWith m ...

  9. leetcode面试准备:Sliding Window Maximum

    leetcode面试准备:Sliding Window Maximum 1 题目 Given an array nums, there is a sliding window of size k wh ...

随机推荐

  1. linux配置学习笔记(一):如何提高ssh连接的速度

    服务器端sshd配置文件 /etc/ssh/sshd_config 看是否有如下的两条配置条目 GSSAPIAuthentication no UseDNS no 如果前面带#,请把#删掉,或者新添加 ...

  2. SQLServer 2008数据库查看死锁、堵塞的SQL语句

      --每秒死锁数量 SELECT * FROM sys.dm_os_performance_counters WHERE counter_name LIKE 'Number of Deadlocks ...

  3. 使用info.plist(或工程名-info.plist)向程序中添加软件Build ID或者版本号信息

    在实际应用程序开发过程中,经常需要向程序中添加软件版本号或者类似的信息,以保证之后发现问题时知道bug所在的版本,我们可以通过在工程名-info.plist文件中设置相关的key/value对(键/值 ...

  4. NSArray函数

    1.判断是否包含某一个元素,返回1则表示有 - (BOOL)countainsObject:(id)anObject BOOL isContain = [arrayboy containsObject ...

  5. 信鸽推送.net 服务端代码

    //推送代码 private void send() { #region 安卓推送 XingeApp app = new XingeApp("accessId", "se ...

  6. undrop for innodb c_parser 源码分析

    一,主函数功能: 1,分析命令行参数,保存在全局变量中; 2,打开文件,加载表定义sql,调用分析函数开始处理; 3,打印导入数据的sql语句; 二,文件处理函数,void process_ibfil ...

  7. 九度OJ 1348 数组中的逆序对 -- 归并排序

    题目地址:http://ac.jobdu.com/problem.php?pid=1348 题目描述: 在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对.输入一个数组,求 ...

  8. Ext 面向对象程序设计 入门篇

    ------ 命名空间 定义:对于类的组织定义方式代码: Ext.namespace("Ext.xgao"); ------ 类实例属性 定义:对于一个实例的特征描述代码: Ext ...

  9. Putty终端 模拟 远程登录 虚拟机Linux

    1.虚拟机设置 虚拟机设置->网络适配器->选择Host-only:与主机共享一个私有网络 桥接.NAT.Host-only三种网络模式的说明: (1)桥接:表示在局域网内是一台真实的系统 ...

  10. jQuery.hhNewSilder 滚动图片插件

    /**  * jQuery.hhNewSilder 滚动图片插件  * User: huanhuan  * QQ: 651471385  * Email: th.wanghuan@gmail.com ...