【leetcode刷题笔记】Triangle

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.



题解:典型的动态规划,开始的想法是用一个二维数组sum,sum[i][j]表示从第一行第一列走到(i,j)所得的最小和。那么sum[i,j] = triangle[i,j] + sum[i-1,j-1](注意下表越界判断)。最后返回sum最后一行中最小的元素。

代码如下:

 1 public class Solution {
 2     public int minimumTotal(List<List<Integer>> triangle) {
 3         if(triangle == null || triangle.size() == 0)
 4             return 0;
 5
 6         int length = triangle.size();
 7         int[][] sum = new int[length][length];
 8
 9         for(int i = 0;i < triangle.get(0).size();i++)
10             sum[0][i]= triangle.get(0).get(i);
11
12         for(int i = 1;i < length;i++){
13             for(int j = 0;j < triangle.get(i).size();j++){
14                 int left = j-1>=0?sum[i-1][j-1]:Integer.MAX_VALUE;
15                 int middle = j>triangle.get(i).size()-2?Integer.MAX_VALUE:sum[i-1][j];
16
17                 sum[i][j]  = triangle.get(i).get(j) +  Math.min(left, middle);
18             }
19         }
20
21         int answer = Integer.MAX_VALUE;
22         for(int i = 0;i < triangle.get(length-1).size();i++)
23             answer = Math.min(answer, sum[length-1][i]);
24
25         return answer;
26     }
27 }

上述的解法是O(n2)的空间复杂度,实际上在计算当前行sum的时候我们只用到了上一行的sum值,所以我们可以只保存上一行元素的sum值。但是有一点要注意,如果直接把sum降维成一维数组并且按照从左往右的顺序计算sum是不正确的。例如如下的例子

[
     [-1],
    [-2,-3],
] 

在计算第二行的时候,sum=[-1,0],当计算到元素-2所对应的sum时,sum被更新为[-3,0],那么在计算-3所对应的sum的时候需要的上一行元素对应的-1就丢失了,会得到-3对应的sum为-6的错误结果。所以我们在计算当前行元素的时候,要从后往前计算,就不会把计算下一个元素要用到的数据弄丢了。

最后空间复杂度为O(n)的代码如下:

 1 public class Solution {
 2     public int minimumTotal(List<List<Integer>> triangle) {
 3         if(triangle == null || triangle.size() == 0)
 4             return 0;
 5
 6         int length = triangle.size();
 7         int[] sum = new int[length];
 8
 9         for(int i = 0;i < triangle.get(0).size();i++)
10             sum[i]= triangle.get(0).get(i);
11
12         for(int i = 1;i < length;i++){
13             for(int j = triangle.get(i).size()-1;j>=0;j--){
14                 int left = j-1>=0?sum[j-1]:Integer.MAX_VALUE;
15                 int middle = j>triangle.get(i).size()-2?Integer.MAX_VALUE:sum[j];
16
17                 sum[j]  = triangle.get(i).get(j) +  Math.min(left, middle);
18             }
19         }
20
21         int answer = Integer.MAX_VALUE;
22         for(int i = 0;i < triangle.get(length-1).size();i++)
23             answer = Math.min(answer, sum[i]);
24
25         return answer;
26     }
27 }

【leetcode刷题笔记】Triangle

时间: 2024-07-30 17:57:22

【leetcode刷题笔记】Triangle的相关文章

【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,3,1]. Note:Could you optimize your algorithm to use only O(k) extra space? 题解:简单的模拟题,每次用answer列表存放上一层的值,用temp列表存放当前层的值,只要计算好temp中需要重新计算的元素的索引范围[1,i-1]

【leetcode刷题笔记】Sum Root to Leaf Numbers

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. An example is the root-to-leaf path 1->2->3 which represents the number 123. Find the total sum of all root-to-leaf numbers. For example, 1 / 2 3 T

【leetcode刷题笔记】Longest Consecutive Sequence

Given an unsorted array of integers, find the length of the longest consecutive elements sequence. For example,Given [100, 4, 200, 1, 3, 2],The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4. Your algorithm should run in

【leetcode刷题笔记】Remove Duplicates from Sorted Array II

Follow up for "Remove Duplicates":What if duplicates are allowed at most twice? For example,Given sorted array A = [1,1,1,2,2,3], Your function should return length = 5, and A is now [1,1,2,2,3]. 题解: 设置两个变量:右边kepler和前向游标forward.如果当前kepeler所指的元素和

【leetcode刷题笔记】Restore IP Addresses

Given a string containing only digits, restore it by returning all possible valid IP address combinations. For example:Given "25525511135", return ["255.255.11.135", "255.255.111.35"]. (Order does not matter) 题解:深度优先搜索.用resul

【leetcode刷题笔记】Path Sum

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. For example:Given the below binary tree and sum = 22, 5 / 4 8 / / 11 13 4 / \ 7 2 1 return true, as t

【leetcode刷题笔记】Insertion Sort List

Sort a linked list using insertion sort. 题解:实现链表的插入排序. 要注意的地方就是,处理链表插入的时候尽量往当前游标的后面插入,而不要往前面插入,后者非常麻烦.所以每次利用kepeler.next.val和head.val比较大小,而不是kepeler.val和head.val比较大小,因为如果用后者,要把head指向的节点插入到kepeler指向的节点的前面,如果kepeler指向的节点是头结点,就更麻烦了. 代码如下: 1 /** 2 * Defi

【leetcode刷题笔记】Max Points on a Line

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line. 题解: 思路比较简单,每条直线都可以表示为y=kx+b,所以对于任意三点,如果它们共线,那么它们中任意两点的斜率都相等. 所以就遍历points数组,对其中的每一个元素计算它和位于它后面的数组元素的斜率并保存在一个hashmap中. 这个hashmap的键就是两点构成直线的斜率,值就是和当前元素po

【leetcode刷题笔记】Spiral Matrix II

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. For example,Given n = 3, You should return the following matrix: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ] 题解:以前做过的Spiral Matrix是给一个矩阵螺旋式的输出,这道题是给一个n,螺旋式的