题目的大体要求如下:
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.
大体的意思就是给你一个三角形的二维数组,让你给出从顶到底的路径最小的和,注意的是从一层到下一层必须是相邻的数字,即(2->3或4, 3->6或5,4->5或7等等)。
一.我的解法
首先,这类路径最小的问题基本上会想到用DP的方法求解,但是我尝试了从顶到底的DP后,发现问题很多,因为自顶向下的状态转移方程是: MIN(0,0)=Math.min(MIN(1,0),MIN(1,1))+triangle[0][0];
MIN(1,0)=Math.min(MIN(2,0),MIN(2,1))+triangle[1][0];
…
显然,方程中含有未知数,所以最后无法判断最小路径和的正确值,并且也要耗费O(
n2
n
2
)的空间。当然,自顶向下的DP可以把三角形的两条腰初始化,这样只要选出最后一行的最小值就是答案了。
时间复杂度是O(n)。
其中n指的是三角形中数字的个数。
class Solution{
public int minimumTotal(List<List<Integer>> triangle){
if(triangle.size()==0) return 0;
if(triangle.size()==1) return triangle.get(0).get(0);
int rows=triangle.size();
int[][] dp=new int[rows][rows];
dp[0][0]=triangle.get(0).get(0);
for(int i=1;i<rows;i++)
for(int j=0;j<i+1;j++)
{
if(j==0)
{
dp[i][j]=dp[i-1][j]+triangle.get(i).get(j);
}
else if(j==i)
{
dp[i][j]=dp[i-1][j-1]+triangle.get(i).get(j);
}
else
{
dp[i][j]=Math.min(dp[i-1][j-1],dp[i-1][j])+triangle.get(i).get(j);
}
}
int min=Integer.MAX_VALUE;
for(int i:dp[rows-1])
min=Math.min(i,min);
return min;
}
}
如果是用自底向上的DP求解的话,会简化许多。因为自底向上是先求子问题,再求父问题。不存在未知数,并且可以通过维护底部向量将空间耗费降低到O(n),n是指三角形底部的数字个数。
时间复杂度也是O(n),n是指整个三角形的数字个数。
class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
if(triangle.size()==0) return 0;
int rows=triangle.size();
int[] dp=new int[rows+1];
for(int i=rows-1;i>=0;i--)
for(int j=0;j<=i;j++)
{
dp[j]=Math.min(dp[j],dp[j+1])+triangle.get(i).get(j);
}
return dp[0];
}
}
如果有什么错误或者可以改进的地方,请及时指出,我会积极改进。