经典dp....
可以不用extra空间的,既然要求只能用O(n)...那估计想考滚动数组吧
那就那么写吧。。。
class Solution { public: int minimumTotal(vector<vector<int> > &triangle) { int n = triangle.size(); if(n == 0) return 0; int m = triangle[n - 1].size(); vector<vector<int> > f(2 , vector<int>(m , INT_MAX)); int mark = 0; f[mark][0] = triangle[0][0]; mark ++; mark = mark %= 2; for(int i = 1 ; i < n ; i++){ int len = triangle[i].size(); f[mark][0] = f[(mark+1)%2][0] + triangle[i][0]; for(int j = 1 ; j < len ; j++){ f[mark][j] = min(f[(mark+1)%2][j-1] , f[(mark+1)%2][j]) + triangle[i][j]; } mark++; mark %= 2; } mark++;mark %= 2; int ans = INT_MAX; for(int i = 0 ; i < m ; i++) ans = min(ans , f[mark][i]); return ans; } };
by 1957