Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- http://leetcode.com/onlinejudge#question_120
- Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
- For example, given the following triangle
- [
- [2],
- [3,4],
- [6,5,7],
- [4,1,8,3]
- ]
- The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).
- Note:
- 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.
- */
- class Solution {
- public:
- typedef size_t level_pos_t; // rectangle level no
- typedef size_t row_pos_t; // position within triangle row
- typedef std::pair<level_pos_t, row_pos_t> tri_pos_t; // position within triangle
- typedef std::map<tri_pos_t, int> cache_t; // mapping: position -> return
- typedef std::vector<int> row_t;
- typedef std::vector<row_t> tri_t;
- int minTriPath(const tri_t & T, const tri_pos_t & pos, cache_t & cache)
- {
- const level_pos_t & level = pos.first;
- const row_pos_t & row = pos.second;
- if(level >= T.size() || row >= T[level].size()) { return 0;}
- cache_t::iterator cache_pos = cache.find(pos);
- if(cache.end() != cache_pos) { return cache_pos->second; }
- const int L = minTriPath(T, std::make_pair(level+1, row), cache);
- const int R = minTriPath(T, std::make_pair(level+1, row+1), cache);
- const int ret = T[level][row] + std::min(L, R);
- cache[pos] = ret;
- return ret;
- }
- int minimumTotal(tri_t &T) {
- cache_t cache;
- return minTriPath(T, make_pair(0,0), cache);
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment