您的位置:首页 > 其它

Leetcode 120 Triangle

2013-02-21 22:06 375 查看
//L120 Triangle

//!!!IMPORTANT:erase an DP array to save space, if we only count numbers rather than to know the path

//edge case: NULL

//thoughts:DP, use a arr
to store the smallest element in every line, each element in arr[] represents the smaller ele in the bottom line corresponding to this ele

//construct from the bottom line

//a little detail:

//we compare triangle[i][j]+arr[j] with triangle[i][j+1]+arr[j+1], the smaller is written to arr[j](i from 1 to n,j from 0 to i-2)

//when we reach the arr[i-1], then we finished this line

int minimumTotal(vector<vector<int> > &triangle)
{
if (triangle.empty())
return 0;
int n = triangle.size();
int arr
; //a new feature supported by C99
memset(arr, 0,n * sizeof(int)); //clear the temp array
int i, j;
for (i = n - 1; i >= 0; i--)
{
for (j = 0; j < i; j++)
{
arr[j] = std::min(triangle[i][j] + arr[j],
triangle[i][j + 1] + arr[j + 1]);
}
}
return triangle[0][0] + arr[0]; //return the top elemnt plus the smaller of its two "childeren"
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: