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. unity访问php

    长连接,弱联网.不好意思,这俩不是一个意思. 反过来说,短连接,强联网,是不是有点别扭呢. 你可以不会php,甚至你可以不知道php是干什么的. 百度php安装环境,自行搭建好环境,顺便测试一下.(下 ...

  2. ajax跨域请求的解决方案

    一直打算改造一下自己传统做网站的形式. 我是.Net程序员,含辛茹苦数年也没混出个什么名堂. 最近微信比较火, 由于现在大环境的影响和以前工作的总结和经验,我打算自己写一个数据,UI松耦合的比较新潮的 ...

  3. java web-----MVC设计模式

    一,MVC将代码分为三个部分,分别为视图(jsp),模型(javaBean),控制部分(servlet); 视图基本为 jsp 文件,主要内容为界面的html代码,负责显示界面: 模型为 javaBe ...

  4. 暑假集训(3)第四弹 -----Frogger(Poj2253)

    题意梗概:青蛙王子最近喜欢上了另一只经常坐在荷叶上的青蛙公主.不过这件事不小心走漏了风声,被某fff团团员知 道了,在青蛙王子准备倾述心意的那一天,fff团团员向湖泊中注入大量的充满诅咒力量的溶液.这 ...

  5. async:false同步请求,浏览器假死

    // 异步请求导致数据错乱 // function get_num(){ // $("input[name='monitor']").eq(1).attr('checked',tr ...

  6. 排序算法TWO:快速排序QuickSort

    import java.util.Random ; /** *快速排序思路:用到了分治法 * 一个数组A[0,n-1] 分解为三个部分,A[0,p - 1] , A[p] , A[p + 1, n-1 ...

  7. SSH+Ajax实现用户名重复检查(二)

    1.另外一种更常用的js表达方式: var user = { inintEvent: function(){ $("input[name='user.User_LogName']" ...

  8. Java知识总结--三大框架

    1 应用服务器有哪些:weblogic,jboss,tomcat 2 Hibernate优于JDBC的地方 1)对jdbc访问数据库进行了封装,简化了数据访问层的重复代码 2)Hibernate 操作 ...

  9. DataGridView绘制序号

    1.找到RowPostPaint事件 2.写入事件 /// <summary> /// 绘制序号 /// </summary> private void dgvStatemen ...

  10. DataGridView几个基本属性

    DataGridView 经常用到,但是很多东西都不熟悉,以至于总去上网查,这次我整理一下,全部都记下来,再用就方便了. 1.禁止用户新建行,就是去掉最后那个行标题上带星号的那个行 dataGridV ...