题目得说明路径不能跨越,否则的话,每层找最小的就可以了。为什么多提交两次呢?dp[j] = (dp[j]>dp[j+1]?dp[j+1]:dp[j]) + triangle[i][j];要是条件表达式不加括号的话不可以,那样的话后面的加法就没加上。还有一点就是j从小到大遍历,否则的话会覆盖结果,正常人都会从小到大。
// LeetCode_Triangle.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
int minimumTotal(vector<vector<int> > &triangle) {
int row = triangle.size();
int column;
int ret = 0;
if(row!=0)
column = triangle[row-1].size();
else
return ret;
int *dp = new int[column];
for(int i=0;i<column;i++)
dp[i] = triangle[row-1][i];
for (int i=row-2;i>=0;i--)
{
for (int j=0;j<=i;j++)
{
dp[j] = (dp[j]>dp[j+1]?dp[j+1]:dp[j]) + triangle[i][j];
}
}
ret = dp[0];
delete[] dp;
return ret;
}
int _tmain(int argc, _TCHAR* argv[])
{
vector<int> temp;
vector<vector<int> > tri;
temp.push_back(-1);
tri.push_back(temp);
temp.clear();
temp.push_back(2);
temp.push_back(3);
tri.push_back(temp);
temp.clear();
temp.push_back(1);
temp.push_back(-1);
temp.push_back(-1);
tri.push_back(temp);
cout<<minimumTotal(tri);
system("pause");
return 0;
}