设定F(i) i=1..n,是以第n行的第i个元素为结束的最短路径和
假设第n-1行的F(1)..F(n-1)已经计算完毕,那么在计算第n行的F(1)..F(n)时,可以
当i <=n-1时, F(i) = min(F(i-1), F(i)) +triangle[n-1][i-1];
当 i=n 时,F(i) = F(i-1) +triangle[n-1][i-1];因为n-1行并没有只有n-1个元素,没有计算F(n)。
F(i)可以使用n+1个元素的一维数组表示,更新发F(i-1)前先保存老值,因为计算F(i)时需要用到
代码如下:
int minimumTotal(vector<vector<int> > &triangle) { uint32_t n = triangle.size(); int *minPathSum = new int[n+1]; if (minPathSum == nullptr) { return 0; } else { memset(minPathSum, 0, sizeof(int)*(n+1)); } for (uint32_t i = 1; i <= n; i++) { int curMin = 0; int nextMin = 0; for (uint32_t j = 1; j <= i; j++) { if (j == 1) { curMin = minPathSum[j]; } else { curMin = nextMin; } if ((j+1) <= (i-1)) { nextMin = std::min(minPathSum[j], minPathSum[j+1]); } else { nextMin = minPathSum[j]; } minPathSum[j] = curMin + triangle[i-1][j-1]; } } int result = minPathSum[1]; for (uint32_t i=1; i <= n; i ++) { if (result > minPathSum[i]) { result = minPathSum[i]; } } delete [] minPathSum; minPathSum = nullptr; return result; }