Leetcode Triangle
http://oj.leetcode.com/problems/triangle/
一道动态规划的经典题,POJ 1163 也是同一类型题,唯一区别在于Leetcode求最小值,POJ 1163求最大值。
递推公式是关键,假设原数组可以被修改,递推公式为:array[i][j] = array[i][j] + Math.max(array[i-1][j-1],array[i-1][j]);
从上向下每个路径的最小值都由上层的两个相邻节点决定。
发现从下向上计算的话,可以少考虑很多边界问题。
POJ 1163 AC的代码如下所示:
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int count = scan.nextInt();
int [][] array = new int [count][count];
for(int i=0;i<count;i++) {
for(int j=0;j<=i;j++) {
array[i][j] = scan.nextInt();
}
}
if (count>1) {
for(int i=count-2;i>=0;i--) {
for(int j=0;j<count-1;j++) {
array[i][j] = array[i][j] + Math.max(array[i+1][j],array[i+1][j+1]);
}
}
}
if(count==0) {
System.out.println(0);
} else {
System.out.println(array[0][0]);
}
}
}
Leetcode Triangle AC的代码如下所示:
public class Solution {
public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
// Start typing your Java solution below
// DO NOT write main() function
for(int i = triangle.size() - 2; i >= 0; i--)
{
for(int j = 0; j < triangle.get(i).size(); j++)
{
triangle.get(i).set(j, triangle.get(i).get(j) + Math.min(triangle.get(i + 1).get(j), triangle.get(i + 1).get(j + 1)));
}
}
return triangle.get(0).get(0);
}