Monday, May 18, 2015

Triangle

来源:Leetcode

原帖:https://oj.leetcode.com/problems/triangle/

题目:
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.

Solution: Note that there are n elements in the n-th row (n starts from 1).
           1. DFS. (Time Limit Exceeded for large test data).
           2. DP. Do not need additional spaces (happen in-place).
           3. DP. O(n) space (If the input 'triangle' can not be changed).

代码:
 class Solution {  
 public:  
   //top -> bottom  
   int minimumTotal(vector<vector<int>> &triangle) {  
     int res = INT_MAX;  
     minimumTotalHelper(triangle, 0, res, 0, 0);  
     return res;  
   }  
   
   void minimumTotalHelper(vector<vector<int>> &triangle, int partSum, int &res, int deep, int pos) {  
     if (deep == triangle.size()) {  
       res = min(res, partSum);  
       return;  
     }  
     // 'pos' start position at level 'deep'  
     for (int i = pos; i < triangle[deep].size() && i <= pos + 1; ++i) {  
       minimumTotalHelper(triangle, partSum + triangle[deep][i], res, deep + 1, i);  
     }  
   }  
 };  
   
 class Solution {  
 public:  
   int minimumTotal(vector<vector<int>> &triangle) {  
     // bottom to up  
     for (int i = triangle.size() - 2; i >= 0; --i) {  
       for (int j = 0; j < i + 1; ++j) {  
         triangle[i][j] = triangle[i][j] + min(triangle[i + 1][j], triangle[i + 1][j + 1]);        
       }  
     }  
     return triangle[0][0];  
   }  
 };  
   
 class Solution {  
 public:  
   //Version 3: dp[n], bottom to up  
   int minimumTotal(vector<vector<int>> &triangle) {  
     int N = triangle.size();  
     vector<int> dp(N, 0);  
     for (int i = 0; i < N; ++i) {  
       dp[i] = triangle[N - 1][i];  
     }   
     for (int i = N - 2; i >= 0; --i) {  
       for (int j = 0; j < i + 1; ++j) {  
         dp[j] = triangle[i][j] + min(dp[j], dp[j + 1]);  
       }  
     }  
     return dp[0];  
   }  
 };  
   

No comments:

Post a Comment