runnig

[leetcode] 120 Min Triangle Path

Feb 2nd, 2013
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.65 KB | None | 0 0
  1. /*
  2. http://leetcode.com/onlinejudge#question_120
  3.  
  4. Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
  5.  
  6. For example, given the following triangle
  7. [
  8.      [2],
  9.     [3,4],
  10.    [6,5,7],
  11.   [4,1,8,3]
  12. ]
  13. The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).
  14.  
  15. Note:
  16. 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.
  17. */
  18. class Solution {
  19. public:
  20.     typedef size_t level_pos_t; // rectangle level no
  21.     typedef size_t row_pos_t; // position within triangle row
  22.     typedef std::pair<level_pos_t, row_pos_t> tri_pos_t; // position within triangle
  23.  
  24.     typedef std::map<tri_pos_t, int> cache_t; // mapping: position -> return
  25.     typedef std::vector<int> row_t;
  26.     typedef std::vector<row_t> tri_t;
  27.    
  28.     int minTriPath(const tri_t & T, const tri_pos_t & pos, cache_t & cache)
  29.     {
  30.         const level_pos_t & level = pos.first;
  31.         const row_pos_t & row = pos.second;
  32.  
  33.         if(level >= T.size() || row >= T[level].size()) { return 0;}
  34.        
  35.         cache_t::iterator cache_pos = cache.find(pos);
  36.         if(cache.end() != cache_pos) { return cache_pos->second; }
  37.        
  38.         const int L = minTriPath(T, std::make_pair(level+1, row), cache);
  39.         const int R = minTriPath(T, std::make_pair(level+1, row+1), cache);
  40.        
  41.         const int ret = T[level][row] + std::min(L, R);
  42.        
  43.         cache[pos] = ret;
  44.         return ret;        
  45.     }
  46.     int minimumTotal(tri_t &T) {
  47.         cache_t cache;
  48.         return minTriPath(T, make_pair(0,0), cache);        
  49.     }
  50. };
Advertisement
Add Comment
Please, Sign In to add comment