被402折磨的不要不要的。时隔了四年重新捡起了在学校公寓北门5块钱盗版的《C和指针》,突然觉得习惯了高级语言,重新静下心来研究C这样的底层语言有一种不一样的感觉,自己第一个接触的编程语言就是C,当时候指针引用这些概念理解的糊里糊涂的。现在突然觉得这种能吆喝操作系统还能吆喝硬件的语言还是有点牛逼的。
好了不废话了,上题!
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).
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.
在lintcode中,这道题给的函数参数类型是数组,我第一个想到的解法就是暴力遍历然后更新全局变量。
public class Solution {
/**
* @param triangle: a list of lists of integers.
* @return: An integer, minimum path sum.
*/
int best = Integer.MAX_VALUE;
public int minimumTotal(int[][] triangle) {
// write your code here
if(triangle.length == 1){
return triangle[0][0];
}
traverse( 0 , 0 , 0 , triangle);
return best;
}
void traverse(int x , int y , int sum , int[][] A){
if( x == A.length){
if( sum < best){
best = sum;
}
return;
}
traverse( x+1 , y , sum+A[x][y] , A);
traverse( x+1 , y+1 , sum+A[x][y] , A);
}
}
等于就是把这个数组当做了二叉树来做DFS,如果sum比全局变量小的就更新全局变量。但是后来发现有一个测试用例过不了- -。
那个测试用例是长这个样子的:
[[46],[43,61],[10,-16,3],[-26,41,36,-72],[-28,-76,-22,26,51],[56,-53,38,67,86,-45],[58,53,47,-52,-54,-95,56],[-54,-93,58,68,26,-4,-45,86],[75,28,27,12,33,98,35,87,1],[-13,20,25,-98,-13,11,-44,-77,-59,-97],[-53,-14,83,80,31,89,38,-1,15,-88,53],[-22,86,-41,-94,-25,68,-96,87,55,-18,-49,-25],[-93,-48,39,17,8,61,57,-13,-92,-79,-29,87,51],[-63,3,-72,29,-9,57,-93,-46,-84,88,29,83,69,-7],[15,-49,43,90,-43,94,29,50,-21,-33,-16,43,-26,4,90],[-61,-67,-96,18,-63,32,-91,93,16,-61,86,4,67,46,-27,-63],[-38,0,79,-48,56,51,80,-17,-70,-53,67,49,-3,-52,39,12,-43],[43,-93,-7,-48,91,-13,44,-69,-27,-74,74,95,-25,-88,-43,75,90,8],[8,41,-35,91,48,-12,35,-3,62,59,-86,-49,-83,56,-42,-14,84,-74,72],[6,-44,-78,31,-92,-82,-94,-81,-49,57,85,36,-34,4,77,-66,-71,-34,45,25],[-95,4,15,-45,-3,-52,-11,83,-67,15,32,38,47,54,-54,54,48,-72,72,75,85],[35,11,-72,-61,-11,-62,-33,31,82,68,35,-37,-16,66,37,31,-44,20,40,47,-71,-45],[-6,59,0,-51,7,5,97,-40,-10,32,70,-6,47,-41,31,-86,89,-10,59,1,29,-57,-32],[-34,73,0,62,-9,-53,91,45,17,50,-54,65,-65,50,40 ...
早就上天了。
当然这道题是DP入门的一道经典之题。今天遇到这个问题觉得挺有意思,就把自己犯得一个错误PO上来。